【问题标题】:Linq to Entities IncludeIf Extension [closed]Linq to Entities IncludeIf Extension [关闭]
【发布时间】:2013-08-15 17:56:02
【问题描述】:

在我的存储库中,我发现来自该线程 (LINQ to SQL Where Clause Optional Criteria) 的 WhereIf Linq-to-sql 扩展非常有用,尤其是 IEnumerable 版本。

我想对 Include() 语句做同样的事情,但我不太擅长编写扩展。我被困在扩展的声明上。

谁能帮我将 WhereIf 扩展移植到 IncludeIf?

【问题讨论】:

    标签: 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;
            }            
        }
    }
    

    请记住,您需要像我一样将它们放在静态类中。

    【讨论】:

    • 完美!感谢您的协助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多