The entity cannot be constructed in a LINQ to Entities query

前端 未结 14 2068
失恋的感觉
失恋的感觉 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 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 GetProducts(int categoryID)
    {
        var query = from p in db.Products
                where p.CategoryID == categoryID
                select p;
        var products = query.ToList();
    
        return products;
    }
    

提交回复
热议问题