Read foreign key metadata programatically with Entity Framework 4

前端 未结 2 883
醉酒成梦
醉酒成梦 2020-12-03 00:21

Does anyone know how one goes about obtaining the schema information out of an edmx generated Entity Framework?

Specifically I want to manage to traverse the foreign

相关标签:
2条回答
  • 2020-12-03 00:37

    You can use the following approach --

    foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
    foreach (var entityMember in entity.NavigationProperties)
    foreach (System.Data.Metadata.Edm.EdmProperty foreignKey in entityMember.GetDependentProperties())
    {
        //... use foreignKey
    }
    
    0 讨论(0)
  • 2020-12-03 00:37

    Ended up finding the solution to this. 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.

    0 讨论(0)
提交回复
热议问题