Shantanu Gupta
Shantanu Gupta

Reputation: 21108

Strange behavior of INCLUDE in Entity Framework

This works:

using (var dbContext = new SmartDataContext())
{
    dbContext.Configuration.ProxyCreationEnabled = false;

    var query = dbContext.EntityMasters.OfType<Person>();
    if (includeAddress)
        query.Include(p => p.Addresses);
    if (includeFiles)
        query.Include(p => p.FileMasters);

    output.Entity = query.Include(s=>s.Addresses).FirstOrDefault<Person>(e => e.EntityId == id);
}

while this doesn't:

using (var dbContext = new SmartDataContext())
{
    dbContext.Configuration.ProxyCreationEnabled = false;

    var query = dbContext.EntityMasters.OfType<Person>();
    if (includeAddress)
        query.Include(p => p.Addresses);
    if (includeFiles)
        query.Include(p => p.FileMasters);

    output.Entity = query.FirstOrDefault<Person>(e => e.EntityId == id);
}

I am trying to include Addresses, Files based on boolean flags coming from function. However it seems, EF not including them when using IF condition.

This is related to my previous question which actually worked using Include.

Upvotes: 1

Views: 149

Answers (2)

Aducci
Aducci

Reputation: 26694

You need to assign the result of Include back to query

query = query.Include(p => p.Addresses);

Upvotes: 2

Roy T.
Roy T.

Reputation: 9648

Entity framework's 'Include' function only works when it is connected to the entire linq query that was looking up the entity. This is because the linq query is actually a form of Expression that can be inspected as a whole before it is executed.

In the second example there the Person object is already detached from the database so EF has no information on which table Person came from and how it should join Person with the address table to get the results you want.

If you turn on dynamic proxy generation EF is able to keep track of the relation between the entity and the database. However, I'm not sure if this will make the include statement work.

Upvotes: 0

Related Questions