【问题标题】:I'm getting exception when query with Linq to Entity?使用 Linq to Entity 查询时出现异常?
【发布时间】:2011-03-25 16:52:18
【问题描述】:

这里是例外

无法创建常量值 类型 'System.Collections.Generic.IEnumerable`1'。 只有原始类型('例如 Int32, 支持字符串和 Guid') 这个上下文。

这是我的代码

List<int> items = new List<int>(){1,5,7,14};

var selecteditems = (from u in _entities.UserInfo
                     join type in items on u.TypeID equals  type
                     where u.UserId == userid
                     select new UserClass
                     {
                         FirstName = u.FirstName,
                         LastName = u.LastName
                     }).ToList();

有什么想法会导致异常吗?也许有一些解决方法?

【问题讨论】:

标签: c# linq-to-entities


【解决方案1】:

对于 EF4
去掉 item 上的 join 并将 &amp;&amp; items.Contains(u.TypeID) 添加到 where 子句中。

int[] items = new[] { 1, 5, 7, 14 }; 
var selecteditems = (from u in _entities.UserInfo 
                        where u.UserId == userid && items.Contains(u.TypeID)
                        select new UserClass {
                                            FirstName = u.FirstName, 
                                            LastName = u.LastName, 
                                            Email = ul.Email
                                    }).ToList();

对于 EF1
EF1 不支持集合值参数(即Contains())此post 包含名为BuildContainsExpression 的实用程序方法的代码,可用于绕过此限制。

更新
我更新了答案以反映 Craig Stuntz 关于 EF1 和 EF4 解决方案的 cmets

【讨论】:

  • 我在使用 contains LINQ to Entities 时遇到此错误,无法识别方法 'Boolean Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' 方法,而且这个方法不能翻译成商店表达式。
  • @Jorge 尝试使用 int[] 而不是 List&lt;int&gt; 来处理项目。
  • @Brian:这适用于 int[]List&lt;int&gt;,但需要 EF 4。
  • 我收到此错误消息 = "LINQ to Entities 无法识别方法 'Boolean Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' 方法,而且这个方法不能翻译成商店表达式。”
  • @Jorge: 谷歌BuildContainsExpression
猜你喜欢
  • 1970-01-01
  • 2011-10-10
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多