How to determine if Navigation Property in the Entity Framework is set without loading the related records

爱⌒轻易说出口 提交于 2020-01-21 04:23:26

问题


I'm not sure about Navigational Properties in EF 4 so I would kindly ask you an explanation.

Lets imagine this scenarios:

A)

I have two Entities A and B with a relation N to N (many to many) and tree Table in my Data Base A and B and a Link Table AB with two Foreign Key.

In this scenario EF create a Navigational Property lets call it X and also a XReference.

B)

I have two Entities A and B with a relation 1 to N (one to many) and two Table in my Data Base A and B with one Foreign Key.

In this scenario EF create a Navigational Property lets call it Y but not a YReference.

Now lets take Scenario A and B and try to find out if there is any reference of A in B:

My Code for Scenario:

A):

bool isA = a.XReference.EntityKey != null;

I do not load B records (correct?)

B):

bool isA = a.B.Any(x => x.BId == AId);

I do load B records

My questions:

  • Why EF does not create a YReference and I cannot use EntityKey property in Scenario B.
  • In my Code Scenario B, Do I really do not load any records from B?
  • Do you know a better approach to run this query fast?

Thanks guys for your help, I hope I was able to make it clear :-)


回答1:


Here is a way to check if related records for an entity is loaded or not.

For entity where you have multiple records related to entity you can check like below.(One to many relationship)

myDbContext.Entry(MyEntity).Collection(x => x.NavigationalProperyName).IsLoaded

And If have only one record related to entity, then you can check like below.(One to one relationship)

myDbContext.Entry(MyEntity).Reference(x => x.NavigationalProperyName).IsLoaded



回答2:


Do you mean:

// -to-one relationship
entity.RelatedItemReference.IsLoaded

// -to-many relationship
entity.RelatedItems.IsLoaded


来源:https://stackoverflow.com/questions/6469699/how-to-determine-if-navigation-property-in-the-entity-framework-is-set-without-l

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