The entity cannot be constructed in a LINQ to Entities query

前端 未结 14 2063
失恋的感觉
失恋的感觉 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:57

    You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an anonymous type or onto a DTO:

    public class ProductDTO
    {
        public string Name { get; set; }
        // Other field you may need from the Product entity
    }
    

    And your method will return a List of DTO's.

    public List GetProducts(int categoryID)
    {
        return (from p in db.Products
                where p.CategoryID == categoryID
                select new ProductDTO { Name = p.Name }).ToList();
    }
    

提交回复
热议问题