【问题标题】:The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query无法在 LINQ to Entities 查询中构造实体或复杂类型“AdventureWorks2012Model.Product”
【发布时间】:2014-03-30 07:12:59
【问题描述】:

如您所见,我在使用 Kendo UI 构建数据网格时遇到了这个错误。有没有人能指出我在下面的代码中哪里错了。

 private IEnumerable<Product> GetSubProduct()
         {
             var context = new AdvenDBEntities();
             var subcate = context.Products.Select(p => new Product
             {
                 ProductID = p.ProductID,
                 Name = p.Name,
                 Color = p.Color,
                 ListPrice = p.ListPrice,
             }).ToList();

            return subcate;
          }

错误: The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query. 非常感谢您的宝贵时间!

【问题讨论】:

  • 可能Product 是模型中的实体,尝试创建匿名类型对象。

标签: linq entity-framework asp.net-mvc-4


【解决方案1】:

由于Product 是模型的实体,因此您在选择记录时正在创建该实体的新对象,这不是一个好主意,我不确定模型将如何处理这种行为,这就是它阻止的原因你这样做,(我猜)。无论如何,您可以将代码更改为此,

private IEnumerable<Product> GetSubProduct()
{
    var context = new AdvenDBEntities();
    var subcate = context.Products.ToList();

    return subcate;
}

顺便说一句,您的函数名称表明您缺少Where 子句。

您还可以创建一些自定义 DTO 类并使用它。

例如

class ProductDTO
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public string Color { get; set; }
    public decimal ListPrice { get; set; }
}

private IEnumerable<ProductDTO> GetSubProduct()
{
    var context = new AdvenDBEntities();
    var subcate = context.Products.Select(p => new ProductDTO
                        {
                            ProductID = p.ProductID,
                            Name = p.Name,
                            Color = p.Color,
                            ListPrice = p.ListPrice,
                        }).ToList();

    return subcate;
}

【讨论】:

  • 这正是我想要的,我错过了创建您刚才提到的新 ViewModel ProductDTO。谢谢@sallushan!
【解决方案2】:

我可以为您指出的第一个难闻代码。 DBContext 实现了 IDisposable,因此您有责任在其上调用 Dispose。总之,除了这里的一种情况,使用块

您必须构建查询以获取所有产品,然后从中提取。

private IEnumerable<Product> GetSubProduct()
{
         using (var context = new AdvenDBEntities())
         {
              // Get all constructed type product and then select from it
              var subcate = context.Products
               .ToList()       
               .Select(p => new Product
               {
                 ProductID = p.ProductID,
                 Name = p.Name,
                 Color = p.Color,
                 ListPrice = p.ListPrice,
               });

              return subcate;
        }
 } 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2017-05-31
    • 2015-02-06
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多