The entity cannot be constructed in a LINQ to Entities query

前端 未结 14 2027
失恋的感觉
失恋的感觉 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 07:01

    Here is one way to do this without declaring aditional class:

    public List<Product> GetProducts(int categoryID)
    {
        var query = from p in db.Products
                where p.CategoryID == categoryID
                select new { Name = p.Name };
        var products = query.ToList().Select(r => new Product
        {
            Name = r.Name;
        }).ToList();
    
        return products;
    }
    

    However, this is only to be used if you want to combine multiple entities in a single entity. The above functionality (simple product to product mapping) is done like this:

    public List<Product> GetProducts(int categoryID)
    {
        var query = from p in db.Products
                where p.CategoryID == categoryID
                select p;
        var products = query.ToList();
    
        return products;
    }
    
    0 讨论(0)
  • 2020-11-21 07:01

    In many cases, the transformation is not needed. Think for the reason you want the strongly type List, and evaluate if you just want the data, for example, in a web service or for displaying it. It does not matter the type. You just need to know how to read it and check that is identical to the properties defined in the anonymous type that you defined. That is the optimun scenario, cause something you don't need all the fields of an entity, and that's the reason anonymous type exists.

    A simple way is doing this:

    IEnumerable<object> list = dataContext.Table.Select(e => new { MyRequiredField = e.MyRequiredField}).AsEnumerable();
    
    0 讨论(0)
提交回复
热议问题