The entity cannot be constructed in a LINQ to Entities query

前端 未结 14 2032
失恋的感觉
失恋的感觉 2020-11-21 06:04

There is an entity type called Product that is generated by entity framework. I have written this query

public IQueryable GetProdu         


        
14条回答
  •  难免孤独
    2020-11-21 06:59

    You can project into anonymous type, and then from it to model type

    public IEnumerable GetProducts(int categoryID)
    {
        return (from p in Context.Set()
                where p.CategoryID == categoryID
                select new { Name = p.Name }).ToList()
               .Select(x => new Product { Name = x.Name });
    }
    

    Edit: I am going to be a bit more specific since this question got a lot of attention.

    You cannot project into model type directly (EF restriction), so there is no way around this. The only way is to project into anonymous type (1st iteration), and then to model type (2nd iteration).

    Please also be aware that when you partially load entities in this manner, they cannot be updated, so they should remain detached, as they are.

    I never did completely understand why this is not possible, and the answers on this thread do not give strong reasons against it (mostly speaking about partially loaded data). It is correct that in partially loaded state entity cannot be updated, but then, this entity would be detached, so accidental attempts to save them would not be possible.

    Consider method I used above: we still have a partially loaded model entity as a result. This entity is detached.

    Consider this (wish-to-exist) possible code:

    return (from p in Context.Set()
            where p.CategoryID == categoryID
            select new Product { Name = p.Name }).AsNoTracking().ToList();
    

    This could also result in a list of detached entities, so we would not need to make two iterations. A compiler would be smart to see that AsNoTracking() has been used, which will result in detached entities, so it could allow us to do this. If, however, AsNoTracking() was omitted, it could throw the same exception as it is throwing now, to warn us that we need to be specific enough about the result we want.

提交回复
热议问题