属性选择器和Where T使用Linq查询 [英] Property Selector and Where<T> Query using Linq

查看:144
本文介绍了属性选择器和Where T使用Linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

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();
}

应称为:

Repository.GetByProperty<SomeEntityClass>(Guid.NewGuid(), x => x.MyClassProperty );
Repository.GetByProperty<AnotherEntityClass>(Guid.NewGuid(), x => x.AnotherProperty);

但它不起作用.

有帮助吗?

谢谢.

推荐答案

尝试使用类似的方法:

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();
}

这篇关于属性选择器和Where T使用Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆