开发者

Read foreign key metadata programatically with Entity Framework 4

开发者 https://www.devze.com 2023-01-29 04:12 出处:网络
Does anyone know how one goes about obtaining the schema information out of an edmx generated Entity Framework?

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 key for an entity that I don't currently have an instance of and get the it's foreign key relationships, and I want to do this via reflection in a way that'll be generically applied to any entity class without custom code each time.

EG: My schema has 2 classes, User and Group. I have the number "42" that I know came from the "GroupId" property of a "User开发者_如何学Go" entity, but at the moment I can't work out how to detect that this "GroupId" property of "User" foreign keys to the "Group" entity by it's "GroupId" property.


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
}


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

精彩评论

暂无评论...
验证码 换一张
取 消