create a function to get foreign key column name of entity by passing entity names in a function using Entity framework. RRS feed

  • Question

  • i want to create a function which will return a foreign key property name by passing Master and child entity in a function

    ex- string getForeignKey(MasterEntity me,ChildEntity ce)

       return "ChildEntity foreign key column name which is related to MasterEntity Primary key";


    column means- ChildEntity property name;

    Tuesday, May 1, 2018 10:49 AM

All replies

  • Hi Gajendra Bisht,

    Please try the following steps.

    The relevant information can be found in the context's RelationshipManager property. By calling GetAllRelatedEnds() and then finding the ones of the type AssociationSet.

    The ElementType of the association set then contains an IsForeignKey property and also an array ReferentialConstraints that has properties for each constraint ToRole, ToProperty, FromRole and FromProperty respectively, and the RelationshipMultiplicity on the ToRole/FromRole can be used to determine the direction of the foreign key relationship.

    Taking all this data and using the context's GetObjectByKey method I was able to programatically traverse the foreign key relationships defined for a context without having the associated entity.

    Best regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Wednesday, May 2, 2018 3:10 AM