如何在不访问导航属性的情况下获取外键的值,以便我不需要加载完整的实体?
public class A
{
public int Id {get;set;}
// ...
}
public class B
{
public virtual A A {get;set;}
// ...
}
int idOfA = MyB.A.Id; // slow way of doing it.
我在VS2012中使用Entity Framework 6 ModelFirst + DbContext。 以前我使用过旧的EF版+ ModelFirst + ObjectContext。 我已经咬了一下子弹并通过从旧数据库创建模型进行迁移。
使用旧的ObjectContext获取实体密钥:
EntityReference<EntityType> reference = MyB.AReference; // AReference was generated by EF
int id = (int)reference.EntityKey.EntityKeyValue[0].Value;
但现在代码生成器不再为每个One或ZeroOrOne导航属性生成EntityReferences。
那么如何在EF6 + DbContext中获取外键?
以下是我尝试/可以做但失败/不想要的一些想法:
public int *Id {get;set;}
)。但我从来没有这样做,也不知道从哪里开始阅读。答案 0 :(得分:0)
这是我使用的代码(授予它不是模型优先,但它没有具体的任何方法)。
在样本中我有产品,并且每个产品属于一个类别。以下是我在CategoryId
加载Product
时查询Category
实体中Model1 context = new Model1();
var product = context.Products.First();
RelationshipManager relMgr = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetRelationshipManager(product);
IEnumerable<IRelatedEnd> relEnds = relMgr.GetAllRelatedEnds();
IRelatedEnd relEnd = relEnds.Where(r => r.RelationshipName.EndsWith("Product_Category")).Single();
EntityReference<Category> entityRef = relEnd as EntityReference<Category>;
var entityKey = entityRef.EntityKey;
int categoryId = (int)entityKey.EntityKeyValues[0].Value;
的方法:
explicit wait