How to determine if a navigation property is set in the Entity Framework without loading related records

I'm not sure about the navigation properties in EF 4, so please explain.

Let's look at these scenarios:

BUT)

I have two Entities A and B with a ratio of N to N (many to many) and a table tree in my database A and B and a link table AB with two foreign keys.

In this scenario, EF creates a navigation property by calling it X , as well as XReference .

IN)

I have two Entities A and B with a 1 to N ratio (one to many) and two tables in my database A and B with one foreign key.

In this scenario, EF creates a navigation property, calling it Y , but not YReference .

Now let's take scenarios A and B and try to find out if there is any link A in B:

My code for the script:

BUT):

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

I do not load B records (right?)

IN):

 bool isA = aBAny(x => x.BId == AId); 

I load records B

My questions:

  • Why does EF not create a YReference, and I cannot use the EntityKey property in script B.
  • In my code script B, am I really not loading records from B?
  • Do you know that it is better to use this query faster?

Thanks guys for your help, I hope I could clarify :-)

+7
source share
2 answers

Here's how to check if related records are loaded for an object or not.

For an object where you have several entries related to an entity, you can check as shown below. (One-to-Many Relationship)

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

And if there is only one entry related to the entity, then you can check as shown below. (One to one relationship)

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

Do you mean:

 // -to-one relationship entity.RelatedItemReference.IsLoaded // -to-many relationship entity.RelatedItems.IsLoaded 
+1
source

All Articles