Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :-)

like image 996
GibboK Avatar asked Jun 24 '11 15:06

GibboK


2 Answers

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
like image 139
Arjun Vachhani Avatar answered Nov 15 '22 15:11

Arjun Vachhani


Do you mean:

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

// -to-many relationship
entity.RelatedItems.IsLoaded
like image 37
Lawrence Wagerfield Avatar answered Nov 15 '22 15:11

Lawrence Wagerfield