c# - 如何克服简单 WHERE 语句的 "Unable to create a constant value of type ..."异常

标签 c# linq entity-framework-4

我使用具有以下定义的 EF:

public class StoredFile
{
    public int StoredFileId { get; set; }
    public HashCode HashCode { get; set; }
    public string LocalName { get; set; }
    //and some more fields here...
}

[ComplexType]
public class HashCode
{
    public Byte [] ValueArr {get; set;}
    public override bool Equals(object o) {...}
    //some more methods to manipulate hash codes                
}

我正在尝试让以下查询工作:

    public bool TryGetFileInfo(MachineSafeDbDataContext dataContext, HashCode hash, out StoredFile fileInfo)
    {
        var matches = from curr in dataContext.StoredFiles where (hash.Equals(curr.HashCode)) select curr;

        if (matches.Count() == 0)
        {
            fileInfo = null;
            return false;
        }

        fileInfo = matches.First();
        return true;
    }

但是我收到“无法创建类型...的常量值”异常。我猜想 LINQ 无法找到上述 WHERE 语句的 SQL 转换。

我知道以下问题:Entity Framework - "Unable to create a constant value of type..." exception ,以及 Microsoft 的以下页面:Known Issues and Considerations in LINQ to Entities 。但是,我仍然想根据哈希码从数据库中选择一个文件。

谢谢

编辑:我应该超越 L2E 限制。这个thread有一些很好的指针和链接。

最佳答案

您无法在 L2E 中调用重写的 .Equals()

但是,您可以直接深入了解 ValueArr:

var matches = from curr in dataContext.StoredFiles 
              where (curr.HashCode.ValueArr == hash.ValueArr) 
              select curr;

关于c# - 如何克服简单 WHERE 语句的 "Unable to create a constant value of type ..."异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567988/

相关文章:

.net - Linq 查询不返回 IEnumerable

c# - LINQ Guid toString()

c# - LINQ 查询,使用分组依据选择最新值 - 不支持的方法

具有多个联接的 ASP.NET linq Select

c# - HashAlgorithm.ComputeHash() 是有状态的吗?

c# - 安装后运行我的应用程序时没有任何反应

c# - 在 C# 中使用百分比值调整图像大小

c# - 正确使用 BeginReceive/EndReceive?

entity-framework-4 - Entity Framework GroupBy 对象或 ComplexType

entity-framework - Entity Framework 代码优先和搜索标准