【问题标题】:Where In clause against nullable field in Linq针对 Linq 中可空字段的 Where In 子句
【发布时间】:2012-08-07 05:57:09
【问题描述】:

如何编写 Linq to Entities 以创建类似于 SQL Server 中的 where in 子句?问题是我需要搜索的字段是可为空的 int。

我有以下代码,但它返回“无法创建类型为 'System.Collections.Generic.List`1' 的常量值。仅支持原始类型('例如 Int32、String 和 Guid')这个上下文。”

public IList<WantedInfoView> GetWanted(string idList)
{
    List<int> contactIDList = new List<int>();
    contactIDList = idList.Split(',').Select(n => int.Parse(n)).ToList();

    IEnumerable<WantedInfoView> wantedList = (
       from w in db.Wanteds
       where contactIDList.Contains(w.contact_id)
       select new WantedInfoView
       {
           ...
       }
    );
}

【问题讨论】:

  • 哪一行出现错误?
  • 你可能需要做w.contact_id.Value

标签: c# linq entity-framework nullable contains


【解决方案1】:

Collection-valued parameters with The Entity Framework?

接受的答案链接到Tip 8 - How to write 'WHERE IN' style queries using LINQ to Entities,这就是您要查找的内容。

WHERE IN clause 线程似乎也在解决这个问题。

长话短说,您不能在 LINQ to Entities 查询中使用集合作为参数。该框架无法从中进行 SQL 查询。有一些解决方法,虽然不是很漂亮。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多