How to get foreign key value for independent association without hitting database?

馋奶兔 提交于 2019-12-06 03:24:47

It's possible. With your example model you can find the foreign key values the following way:

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

In the more general case where you have multiple relationships in the Bbb class and maybe even more than one navigation property refering to Aaa you need to find the correct element in the relEnds enumeration. You could also have composite foreign keys. It would look like this then:

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

Note, that IsLoaded can be true if you inspect the entityRef object in the debugger which can cause the related object to be loaded (even though lazy loading is disabled).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!