簡體   English   中英

屬性選擇器和位置 <T> 使用Linq查詢

[英]Property Selector and Where<T> Query using 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();
}

你需要在對象上調用選擇器,所以這樣的東西應該工作

public T GetById<T>(Guid id, Func<T, object> idSelector)
{
    return Session.Query<T>().Where(x => idSelector(x) == id).FirstOrDefault();
}

在類似的情況下,我通常使用Single(OrDefault)而不是Where / First(OrDefault)組合,因為我喜歡在某處有重復鍵時拋出異常。

與SWeko的答案類似,允許您鍵入idSelector的替代方法(以防止ObjectGuid比較......)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM