简体   繁体   中英

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.

您需要将Include结果分配回query

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM