2011-04-11 23 views
4

我有以下LINQ声明(的stationID是int和版本是一个字节数组):LINQ实体错误使用SequenceEqual枚举方法

  var foundStation = (from wd in _Context.AssignmentWizardDatas 
       from station in wd.AssignmentWizardStationDatas 
       where station.Id == stationId 
       where station.Version.SequenceEqual(version) 
       select station).SingleOrDefault(); 

当上述代码运行我会遇到以下错误:

LINQ to Entities does not recognize the method 'Boolean SequenceEqual[Byte](System.Collections.Generic.IEnumerable 1[System.Byte], System.Collections.Generic.IEnumerable 1[System.Byte])' method, and this method cannot be translated into a store expression.

经过一番阅读后,我意识到问题是LINQ无法将SequenceEqual方法调用转换为SQL等价物(我认为无论如何)。有没有人知道这个解决方法?或者,当尝试在LINQ查询中使用字节数组时,可能会指向正确的方向,但我找不到专门用于字节数组的现有问题。

在此先感谢。

编辑:使用贾尼的职位,这是用来解决这个错误最终代码:

 //eager execution of the linq query to find the stations 
    var foundStation = (from wd in _Context.AssignmentWizardDatas 
          from station in wd.AssignmentWizardStationDatas 
          where station.Id == stationId 
          select station).ToList(); 
    //finding the result in memory 
     var result = (from f in foundStation 
         where f.Version.SequenceEqual(version) 
         select f).SingleOrDefault(); 

回答

4
//eager execution of the linq query to find the stations 
var foundStation = (from wd in _Context.AssignmentWizardDatas 
        where wd.Id == stationId 
        select station).ToList(); 
//finding the result in memory 
var result = from f in foundStation 
      where f.version.SequenceEqual(version) 
      select f; 
+0

感谢贾尼,你试过这个吗?对我而言,这仍然会引发同样的例外情况? – MattStacey 2011-04-11 13:38:26

+0

但是,当您将代码更改为此时,可能发生的异常与“LINQ to Entities”无关,它将在内存中执行。你确定吗? – 2011-04-11 13:41:50

+0

谢谢。我再次看了一遍,我不认为我在第一个LINQ语句的末尾包含了.ToList()。我已经更新了我的原始问题以显示我使用的最终答案,因为它与您在此处写的内容略有不同。谢谢你的帮助。 – MattStacey 2011-04-11 15:07:44

8

您在您解释的错误的方式是正确的,但你并不需要SequenceEquals()完全可以 - 您可以直接比较数据库中提供的绑定到varbinary(MAX)的字节数组。

var foundStation = (from wd in _Context.AssignmentWizardDatas 
from station in wd.AssignmentWizardStationDatas 
where station.Id == stationId 
where station.Version == version 
select station).SingleOrDefault(); 
+1

是的,当我运行网站时,你是正确的,按预期工作。我在TDD环境中工作,现在有点困惑,因为我最初有这个代码,但是因为它会导致我的单元测试失败而改变它,而使用SequenceEqual方法实际上会传递单元测试,但在运行时遇到异常。你有什么想法,为什么这可能是? – MattStacey 2011-04-11 13:36:48

+3

@MattStacey:这很有道理 - 在你的单元测试中'SequenceEqual()'可以在两个字节数组上工作,但如果直接比较,你只比较引用,所以它们永远不会匹配。单元测试EF实际上击中数据库是非常困难的,因为它们有许多不同之处,您必须考虑。 – BrokenGlass 2011-04-11 13:38:55

+0

我已验证此作品。我们遇到了同样的问题,使用NHibernate,Fluent和Linq2NH。转换为简单的“e.ssn == ssn”,其中ssn是一个varbinary和一个byte [],并开始工作。我假设Linq2NH理解比较并将其转换为适当的HQL,该HQL理解映射+参数类型组合并转换为适当的SQL。 – xero 2011-07-11 21:50:18