我嘗試從edmx文件中獲取實體的FKs的集合。我找不到一個返回集合的方法或屬性,或者只有bool屬性來指示實體的屬性是FK。 我搜索了MetadataProperties中的EntityContainer類,並沒有發現任何東西。我在類中搜索類屬性GetProperties和相同的結果,我找不到方法或屬性來指示FK。 如何從edmx文件中獲得FK或FK實體的指示?從EDMX文件中獲取實體的外鍵
對不起我英語不好。
感謝
我嘗試從edmx文件中獲取實體的FKs的集合。我找不到一個返回集合的方法或屬性,或者只有bool屬性來指示實體的屬性是FK。 我搜索了MetadataProperties中的EntityContainer類,並沒有發現任何東西。我在類中搜索類屬性GetProperties和相同的結果,我找不到方法或屬性來指示FK。 如何從edmx文件中獲得FK或FK實體的指示?從EDMX文件中獲取實體的外鍵
對不起我英語不好。
感謝
你可以找到在實體模型與特定實體的所有外鍵的實體類型以下
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();
您可以使用反射和過濾的ForeignKeyAttribute性能得到Foriegn關鍵。
public static IEnumerable<PropertyInfo> GetForeignKeyProps(Type type) {
return type.GetProperties()
.Where(prop => prop.IsDefined(typeof(ForeignKeyAttribute), false));
}
使用,得到的值:
var obj = new T();
var foreignKeyPropertyInfos = GetForeignKeyProps(typeof (T));
foreach (var foreignKeyPropertyInfo in foreignKeyPropertyInfos)
{
var value = foreignKeyPropertyInfo.GetValue(obj)
}
您可能正在尋找它允許您訪問的導航屬性的對象集(從舊EF)。你可以得到你的手這樣說:
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
var os = objectContext.CreateObjectSet<TEntity>();
var foreignKeyProperties = os.EntitySet.ElementType.NavigationProperties.Where(x => x.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One);
db
是DBContext
,TEntity
是您正在使用
嗨,向我們展示模型,以及您試過的東西 – Jorge
您是否需要物業的價值? – Oliver
模型有超過10 thousend線。我不喜歡把它粘貼在這裏。我不需要價值,只有一些跡象表明財產是外鍵。我在Assosiacations集合和實體集合以及類型typeof(Entity).Properties()中搜索EntityContainer.BaseEntitySets。 – Pimpy