我想在实体模型中找到实体的所有外键。
我使用以下内容获取实体的所有属性列表:
var workspace = _entities.MetadataWorkspace;
var entityType = workspace.GetItems<EntityType>(DataSpace.CSpace).FirstOrDefault(e => e.Name == tablename);
var keyNames = entityType.Members.Select(k => k.Name);
有没有办法只找到那些有外键关联的属性?还有与之关联的参考实体中的那个属性?
答案 0 :(得分:7)
我制定了解决方案:
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();