I have some code that is working, but I don't know how. I'm asking this question in hopes that someone can explain how it is working, as any searching I do online gives me information that's not quite specific to what I'm seeing.
I have two entities.
EntityA, EntityB.
EntityA has this:
public partial class EntityA
{
...
public Guid EntityBGuid { get; set; }
public virtual EntityB EntityB { get; set; }
}
EntityB has this:
public partial class EntityB
{
...
public virtual ICollection<EntityA> EntityAs{ get; set; }
}
Nowhere in DatabaseEntities.cs > OnModelCreating()
is a relationship defined for either entity.
Nowhere in either table in SQL is there a FK defined for the relationship.
So when I do something like this:
context.LettingProjects.Where(query).Select(s => s.Call).ToList(); //Crash.
But with a .Include, I get data:
context.LettingProjects.Include(i => i.Call).Where(query).Select(s => s.Call).ToList(); //Results.
My question is how does this even work? I don't know how EF handles this in the background, and it seems like a gotcha waiting to happen.
When you are writing this:
context.LettingProjects.Where(query).Select(s => s.Call).ToList();
EF will simply query for a single table.
However, as you probably configured the relationships in your models to contain other Tables too (ICollection<EntityA>
), they will contain a null
value because EF will not send a query asking for their data.
My question is, how does this even work? I don't know how EF handles this in the background, and it seems like a gotcha waiting to happen.
The answer to your question now should be simple:
when you write .Include(s => s.OtherTable)
you are asking EF to join your current table data with the one you specified.
EF will use the Foreign Key relationships and will give you back a collection of items with the data for the related tables, too (not null version). That's why it will not fail.
This is very similar to using the LINQ to Entities Join
method, but in this case, it's requiring you to write much less code unless you want to control the join operation by yourself.