Strange behavior of INCLUDE in Entity Framework

眉间皱痕 提交于 2020-01-11 11:17:01

问题


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.


回答1:


You need to assign the result of Include back to query

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



回答2:


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.



来源:https://stackoverflow.com/questions/31327883/strange-behavior-of-include-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!