2012-05-30 173 views
4

我想在實體模型中查找實體的所有外鍵。實體框架查找外鍵

我已經使用下列以獲得實體的所有屬性的列表:

var workspace = _entities.MetadataWorkspace; 
var entityType = workspace.GetItems<EntityType>(DataSpace.CSpace).FirstOrDefault(e => e.Name == tablename); 
var keyNames = entityType.Members.Select(k => k.Name); 

有什麼辦法只找到其中​​有外鍵關聯的那些屬性?還有與之相關的參考實體中的財產?

回答

6

我摸索出瞭解決方案:

var fk = _entities.MetadataWorkspace.GetItems<AssociationType>(DataSpace.CSpace).Where(a => a.IsForeignKey); 
//check if the table has any foreign constraints for that column 
var fkname = fk.Where(x => x.ReferentialConstraints[0].ToRole.Name == tablename).Where(x => x.ReferentialConstraints[0].ToProperties[0].Name == columnname); 
//Get the corresponding reference entity column name 
var refcol = fkname.Select(x => x.ReferentialConstraints[0].FromProperties[0].Name).First();