属性选择器和Where<使用Linq查询
本文关键字:使用 Linq 查询 Where 选择器 属性 | 更新日期: 2023-09-27 18:14:42
我正在尝试:
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();
}
您需要调用对象上的选择器,所以像这样的东西应该可以工作
public T GetById<T>(Guid id, Func<T, object> idSelector)
{
return Session.Query<T>().Where(x => idSelector(x) == id).FirstOrDefault();
}
也不是Where
/First(OrDefault)
组合,在类似的情况下,我通常使用Single(OrDefault)
,因为我喜欢一个异常被抛出,如果有一个重复的键在某处
与SWeko的答案类似,允许您键入idSelector(以防止将Object
与Guid
进行比较…)
public T GetById<T, TKey>(TKey id, Func<T, TKey> idSelector)
{
return Session.Query<T>().FirstOrDefault(x => idSelector(x) == id);
}
你可以这样称呼它:
var result = GetById(guidId, (AnotherEntityClass x) => x.MyClassId);
更多,如果您添加以下类…
public class YetAnotherEntityClass
{
public long MyId {get;set}
}
你仍然可以使用相同的方法…
var result = GetById(12345, (YetAnotherEntityClass x) x=> x.MyId;
如果您发现这将加载整个表,请考虑以下操作:
public T GetFirstByCriterion<T, bool>(Expression<Func<T, bool>> criterion)
{
return Session.Query<T>().FirstOrDefault(criterion);
}
可以用
调用var result = GetFirstByCriterion((AnotherEntityClass x) x => x.AnotherProprty = guidId);