这是可能的。使用您的示例模型,您可以通过以下方式找到外键值:
Bbb bbb = myDbContext.Bbbs.First();
var objectContext = ((IObjectContextAdapter)myDbContext).ObjectContext;
var relMgr = objectContext.ObjectStateManager.GetRelationshipManager(bbb);
var relEnds = relMgr.GetAllRelatedEnds();
var relEnd = relEnds.Single(); // because yor model has exactly one relationship
var entityRef = relEnd as EntityReference<Aaa>;
var entityKey = entityRef.EntityKey;
int foreignKeyValue = (int)entityKey.EntityKeyValues[0].Value;
// to confirm that no database query happened
Console.WriteLine(entityRef.IsLoaded); // outputs false
在更一般的情况下,您在Bbb
类中有多个关系,甚至可能不止一个导航属性引用Aaa
您需要在relEnds
枚举中找到正确的元素。你也可以有复合外键。它看起来像这样:
Bbb bbb = myDbContext.Bbbs.First();
var objectContext = ((IObjectContextAdapter)myDbContext).ObjectContext;
var relMgr = objectContext.ObjectStateManager.GetRelationshipManager(bbb);
var entityRef = relMgr.GetRelatedReference<Aaa>(
"MyEntityNamespace.Bbb_MyIndependentAssociation",
"Bbb_MyIndependentAssociation_Target");
var entityKey = entityRef.EntityKey;
object[] compositeForeignKeyValues =
entityKey.EntityKeyValues.Select(e => e.Value).ToArray();
// to confirm that no database query happened
Console.WriteLine(entityRef.IsLoaded); // outputs false
请注意,如果您在调试器中检查IsLoaded
可能导致加载相关对象的对象(即使禁用延迟加载),也可能是这样。true
entityRef