Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c# - Read foreign key metadata programatically with Entity Framework 4

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" 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...