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);

有没有办法只找到那些具有外键关联的属性?还有与之关联的参考实体中的那个属性?

4

1 回答 1

8

我制定了解决方案:

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();
于 2012-06-06T09:01:00.960 回答