属性选择器和Where <T>使用Linq查询

Yoa*_*. B 4 c# linq lambda

我想这样做:

public class SomeEntityClass
{
    public Guid MyClassProperty {get;set;}
}

public class AnotherEntityClass
{
    public Guid AnotherProperty {get;set;}
}

public T GetByProperty<T>(Guid value, Expression<Func<T, object>> selector)
{
    return = Session.Query<T>().Where(x => selector == value).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

应该叫:

Repository.GetByProperty<SomeEntityClass>(Guid.NewGuid(), x => x.MyClassProperty );
Repository.GetByProperty<AnotherEntityClass>(Guid.NewGuid(), x => x.AnotherProperty);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

有帮助吗?

谢谢.

haz*_*zik 8

尝试使用类似的东西:

public T GetByProperty<T, TValue>(TValue value, Expression<Func<T, TValue>> selector) {
    var predicate = Expression.Lambda<Func<T, bool>>(
        Expression.Equal(selector.Body, Expression.Constant(value)), 
        selector.Parameters
    );

    return Session.Query<T>().Where(predicate).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)