Linq到实体IncludeIf扩展 [英] Linq to Entities IncludeIf Extension
问题描述
在我的存储库中,我发现此线程的WhereIf Linq-to-sql扩展名(
In my repositories, I find that the WhereIf Linq-to-sql extension from this thread (LINQ to SQL Where Clause Optional Criteria) is very useful -- especially the IEnumerable version.
我想对Include()语句做同样的事情,但是我对编写扩展不是很好.我陷入了扩展名的声明.
I would like to do the same thing with the Include() statement, but I'm not very good with writing extensions. I got stuck on the declaration of the extension.
有人可以帮助我将WhereIf扩展名移植到IncludeIf吗?
Can anyone help me port the WhereIf extension to IncludeIf?
推荐答案
有两个 Include(...)
,其中一个已经是 IQueryable< T> <的扩展方法./code>,它是
DbQuery< T>
的一种方法.这应该给您两个扩展 IncludeIf<>
There are two Include(...)
, one that is already an extension method to IQueryable<T>
and one that is a method of DbQuery<T>
. This should give you both extensions IncludeIf<>
public static class QueryableEx
{
public static IQueryable<T> IncludeIf<T, TProperty>(this IQueryable<T> source, bool condition, Expression<Func<T, TProperty>> path) where T : class
{
if (condition)
{
return source.Include(path);
}
else
{
return source;
}
}
public static DbQuery<TResult> IncludeIf<TResult>(this DbQuery<TResult> query, bool condition, string path)
{
if (condition)
{
return query.Include(path);
}
else
{
return query;
}
}
}
请记住,您需要像我一样将它们放在静态类中.
Remember that you need to put them in a static class like I have done.
这篇关于Linq到实体IncludeIf扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!