0

我找到了一些有趣的通用存储库,但我无法弄清楚该函数的作用:PerformInclusions(includeProperties, query);

调用 PerformInclusions,

public T Single(Expression<Func<T, bool>> where, string includeProperties)
        {
            try
            {
                IQueryable<T> query = IDbSet;
                query = PerformInclusions(includeProperties, query);
                return query.Single(where);
            }
            catch (InvalidOperationException ex)
            {
                return null;
            }
        }

执行包含

private static IQueryable<T> PerformInclusions(string includeProperties,
                                                       IQueryable<T> query)
        {
            if (includeProperties != null && includeProperties.Length > 0)
            {
                foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    query = query.Include(includeProperty);
                }
            }
            return query;
        }

我可以使用没有第二个参数的单个函数。

Euser test = Adapter.EuserRepository.Single(u => u.EuserEmail.Equals(user.EuserEmail), "");

所以我有两个问题,函数 PerformInclusions() 做了什么,有人可以给我一个例子,在调用 single() 函数时 includeproperties 是什么。

提前致谢

4

1 回答 1

2

正如@Andrei 所说,这允许您使用熟悉的 EF 包含语法来急切加载导航属性。导航属性急切加载的另一种替代方法是通过 lambdas,如下所示:

    public T GetBy(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
    {
        var result = GetAll();
        if (includes.Any())
        {
            foreach (var include in includes)
            {
                result = result.Include(include);
            }
        }
        return result.FirstOrDefault(predicate);
    }

如果您有一个具有如下导航属性的实体:

public class Test{
    public int Id {get;set;}
    public SomethingElse Thing {get;set;}
}

_repo.Single(t => t.Id == 1, "");或者_repo.GetBy(t => t.Id == 1);

将返回一个Thing为空的实体

_repo.Single(t => t.Id == 1, "Thing");或者_repo.GetBy(t => t.Id == 1, t=>t.Thing);

将返回通过外键填充 Thing 的实体

有关 EF 中导航属性的更多详细信息,请查看我的博客http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first

于 2013-04-23T07:41:37.150 回答