c# - Linq 平等比较不起作用

标签 c# nhibernate

给定这个方法:

internal static IEnumerable<Entity> GetByParentImpl<Entity, TKey>(this ICanGetByParent<Entity, TKey> self, TKey parentId, string fieldName) 
    where Entity : class 
{
    RepositoryBase<Entity> rb = (RepositoryBase<Entity>)self;
    rb.unitOfWork.Begin();

    var entities = rb.unitOfWork.Session.QueryOver<Entity>()
        .Where(e => EqualityComparer<TKey>.Default.Equals(GetId<Entity, TKey>(e, fieldName), parentId))
        .List();

    return entities;
}

还有这个助手:

private static TKey GetId<Entity, TKey>(object obj, string fieldName) where Entity : class
{
    TKey id = default(TKey);

    switch(id.GetType().Name) {
        case "Int32":
            break;
        case "Guid":
            id = (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString((string)typeof(Entity).GetField(fieldName).GetValue(obj));
            break;
    }

    return id;
}

我在我的 linq 语句中遇到了这个异常:

Unrecognised method call: System.Collections.Generic.EqualityComparer`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]:Boolean Equals(System.Guid, System.Guid)

这是什么意思?我什至不确定如何正确调试它。我可以发誓上面的代码是有效的...

最佳答案

您不能以这种方式对 linq 与任何数据库提供程序进行比较。提供者无法将其转换为表达式树。所以你必须在 .ToArray() 之后使用它或者给出一个 Expression<Func<RegisterCardBase, bool>>进入 Where 而不是 lambda。

PS:你为什么要和Guid做这么奇怪的 Action ?它是如何存储在数据库中的?

关于c# - Linq 平等比较不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886558/

相关文章:

SQLite 在内存单元测试中显示 "no such table error"而不是真正的错误消息

c# - 将参数从ConfirmNavigationRequest传递到Prism中的NavigationService

c# - 如何使用C#从字符串列表中提取公共(public)部分

c# - 无法将日历选择的日期放入日期时间 C#

c# - 如何正确使用 HttpClient PostAsync 参数?

c# - 如何在 NHibernate 中映射图像类型?

c# - 将 Visual Studio 升级到 15.5 后缺少 System.Net.Http

c# - nhibernate 3.3 一对多代码映射更新 child 而不是插入

sqlite - nhibernate 事务和单元测试

asp.net-mvc - NHibernate:我如何 XmlSerialize 一个 ISet<T>?