【问题标题】:Linq to Entities IncludeIf Extension [closed]Linq to Entities IncludeIf Extension [关闭]
【发布时间】:2013-08-15 17:56:02
【问题描述】:
【问题讨论】:
标签:
c#
entity-framework
linq-to-entities
【解决方案1】:
有两个Include(...),一个已经是IQueryable<T> 的扩展方法,一个是DbQuery<T> 的方法。这应该给你两个扩展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;
}
}
}
请记住,您需要像我一样将它们放在静态类中。