C# Linq相等比较不工作

C# Linq相等比较不工作,c#,nhibernate,linq,C#,Nhibernate,Linq,鉴于此方法: internal static IEnumerable<Entity> GetByParentImpl<Entity, TKey>(this ICanGetByParent<Entity, TKey> self, TKey parentId, string fieldName) where Entity : class { RepositoryBase<Entity> rb = (RepositoryBase<

鉴于此方法:

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;
}
内部静态IEnumerable GetByParentImpl(此ICANGetByParentSelf、TKey parentId、字符串字段名)
其中实体:类
{
RepositoryBase rb=(RepositoryBase)self;
rb.unitOfWork.Begin();
var entities=rb.unitOfWork.Session.QueryOver()
.Where(e=>EqualityComparer.Default.Equals(GetId(e,fieldName),parentId))
.List();
返回实体;
}
这位助手:

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;
}
private static TKey GetId(object obj,string fieldName),其中Entity:class
{
TKey id=默认值(TKey);
开关(id.GetType().Name){
案例“Int32”:
打破
案例“Guid”:
id=(TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString((string)typeof(Entity).GetField(fieldName).GetValue(obj));
打破
}
返回id;
}
我的linq声明中出现了以下异常:

无法识别的方法调用: System.Collections.Generic.EqualityComparer`1[[System.Guid,mscorlib, 版本=4.0.0.0,区域性=中性, PublicKeyToken=b77a5c561934e089]]:布尔值等于(System.Guid, 系统(Guid)


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

您不能以这种方式将linq与任何数据库提供程序进行比较。提供程序无法将其转换为表达式树。因此,必须在.ToArray()之后使用它,或者在Where中指定一个
表达式,而不是lambda


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

NHibernate的Linq提供程序试图将Linq查询转换为HQL,并最终转换为SQL。默认情况下,NHibernate不支持Where方法中的lambda表达式

但是,NHibernate Linq提供程序是。您可以自己处理各种不受支持的表达式

有一个关于如何扩展Linq提供程序以支持的很好的示例

编辑


我刚刚意识到你使用的是QueryOver,而不是NHibernate Linq。您可能应该删除标记。如果您切换到
session.Query()
,我的答案有点相关。不过,您可能会重新考虑转换
Id
并在
Where

中使用它的方法,我不太了解linq到nhibernate,但从实体框架的背景来看,我怀疑查询提供程序没有Equals方法的翻译。您必须使用表达式或在linq-to-objects中执行它。因此,与其扩展linq提供程序,还有什么更好的方法来比较GUID?@TylerWright既然您只有两种类型,您可以单独执行查询
if(typeof(TKey)==typeof(Guid))else