首页 文章

“Controler中的实体或复杂类型不能在LINQ to Entities查询中构造”

提问于
浏览
3

我在我的控制器中有这个代码

IQueryable<SellingItem> sellingitems = db.SellingItems
            .GroupBy(s => new { s.ItemId ,s.Condition,s.ExpInDays})
            .Select(si => new SellingItem
            {
                Item = si.First().Item,
                Condition = si.First().Condition,
                ExpInDays = si.First().ExpInDays,
                Qty = si.Sum(i => i.Qty),
            });

当我尝试运行它时,我得到一个错误

无法在LINQ to Entities查询中构造实体或复杂类型

现在它在我看来我的linq查询太复杂了,实体框架无法处理,

所以我有2个解决方法,但我不喜欢他们两个 .

1.将整个表加载到内存中并进行如下查询

2.使用SQL语句,它会更快,但不会遵循实体框架规则

有没有更好的办法?

----- UPDATE ---------------------------------

事实证明(非常感谢)

说错了我错了

now it look to me that my linq query is too complex for entity framework to handle,

它没有用,因为我使用相同的类来得到结果 . 我创建了一个新课程,现在它的作品令人惊叹!

1 回答

  • 3

    您无需借助任何解决方法来修复该异常本身 . 问题是 SellingItem 是一个属于您的Entity Framework模型的类 . 其原因在comments on this answer中解释 .

    选择一个匿名对象,如下所示:

    IQueryable<SellingItem> sellingitems = db.SellingItems
    .GroupBy(s => new { s.ItemId ,s.Condition,s.ExpInDays})
    .Select(si => new
    {
        Item = si.First().Item,
        Condition = si.First().Condition,
        ExpInDays = si.First().ExpInDays,
        Qty = si.Sum(i => i.Qty),
    });
    

    或者专门为您要执行的选择创建一个对象:

    public class NewClass
    {
        public ItemClass Item { get;set; }
        public ConditionClass Condition { get;set; }
        public in ExpInDays { get;set; }
        public int Qty { get;set; }
    }
    

    当然,您需要确保此特定类中的类型与其各自的类型相匹配 .

    然后,您可以使用新类来执行选择:

    // Use new class
     IQueryable<SellingItem> sellingitems = db.SellingItems
    .GroupBy(s => new { s.ItemId ,s.Condition,s.ExpInDays})
    .Select(si => new NewClass
    {
        Item = si.First().Item,
        Condition = si.First().Condition,
        ExpInDays = si.First().ExpInDays,
        Qty = si.Sum(i => i.Qty),
    });
    

相关问题