Aar*_*ron 3 extension-methods criteria linq-to-sql
我将如何编写一个名为“IsActive”的简单 LINQ to SQL 扩展方法,该方法将包含对几个不同字段的一些基本条件检查,以便我可以在不重复逻辑的情况下到处重用这个“IsActive”逻辑。
例如,我希望能够做这样的事情:
return db.Listings.Where(x => x.IsActive())
Run Code Online (Sandbox Code Playgroud)
IsActive 将类似于:
public bool IsActive(Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
否则,我将不得不在整个系统中复制一百万个不同查询中相同的旧 where 条件。
注意:方法必须在 SQL 中呈现。
好问题,显然需要能够定义可重用的过滤表达式,以避免在不同的查询中冗余指定逻辑。
此方法将生成一个过滤器,您可以将其传递给 Where 方法。
public Expression<Func<Listing, bool>> GetActiveFilter()
{
return someListing => someListing.Approved && !someListing.Deleted;
}
Run Code Online (Sandbox Code Playgroud)
然后,通过以下方式调用它:
Expression<Func<Filter, bool>> filter = GetActiveFilter()
return db.Listings.Where(filter);
Run Code Online (Sandbox Code Playgroud)
既然用了an Expression<Func<T, bool>>,翻译成sql就没有问题了。
这是一个额外的方法来做到这一点:
public static IQueryable<Filter> FilterToActive(this IQueryable<Filter> source)
{
var filter = GetActiveFilter()
return source.Where(filter);
}
Run Code Online (Sandbox Code Playgroud)
后来,
return db.Listings.FilterToActive();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4092 次 |
| 最近记录: |