【问题标题】:Using .Contains within a linq query returning a SystemException在返回 SystemException 的 linq 查询中使用 .Contains
【发布时间】:2012-02-04 21:44:25
【问题描述】:

我在尝试编写 linq 查询时遇到了一些问题。

我有已修改的产品列表 A,因此我试图从数据库中获取产品列表以允许我将更改应用于它们。

我尝试了 2 个不同的查询

   var query = from p in db.Products
                where products.Select(z => z.id).Contains(p.Id)
                select p;

        var query2 = from p in db.Products where (from o in products
                     select o.id)
                    .Contains(p.Id)
                    select p;

两次尝试都返回错误

base {System.SystemException} = {"无法创建类型为 'ProjectABC.Models.ProductModel' 的常量值。在此上下文中仅支持原始类型('例如 Int32、String 和 Guid')。" }

我做错了什么?

【问题讨论】:

    标签: linq entity-framework


    【解决方案1】:

    前几天我遇到了同样的问题,似乎 EF 不支持 Select().Contains() 而不给出该错误。经过一番测试后,我最终将其拆分为您的情况对应的内容;

    var IDs = products.Select(z=>z.id);
    var query = from p in db.Products
                where IDs.Contains(p.Id)
                select p;
    

    当“产品”集合在内存中时(即来自数据库的 ToList() 的结果),在我的情况下效果很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多