动态添加多个

时间:2017-01-26 17:35:36

标签: entity-framework-6

我把一些助手放在一起,这将允许我按类型注册包含。看起来像这样:

Dictionary<Type, LambdaExpression[]> includes = 
    new Dictionary<Type, LambdaExpression[]>();

我注册包含这样的内容:

public void Add<T>(params Expression<Func<T, object>>[] includes)
{
    this.includes.Add(typeof(T), includes);
}

Add<Customer>(e => 
    e.Address.City.Province.Country,
    e.Products.Select(p => p.Category));

请注意Customer有两个包含。然后我有这个方法,包括类型:

DbSet<T> entitySet = null;

void LoadIncludes()
{
    var includes = Includes.Instance.Get<T>().DirectCast<Expression<Func<T, object>>[]>();

    if (includes != null)
    {
        foreach (var include in includes)
        {
            entitySet.Include(include).Load();
        }
    }
}

获得我的实体时,我这样做:

public T GetById(int id)
{
    LoadIncludes();

    return entitySet.SingleOrDefault(x => x.Id == id);
}

效果很好,但速度太慢了,因为我在.Load()中调用了LoadIncludes()方法。有没有更快的方法来做我想做的事情?

1 个答案:

答案 0 :(得分:2)

您不应该致电Load,而是建立并使用Queryable<T> Include链。

LoadIncludes替换为私有函数:

private IQueryable<T> GetEntitySet()
{
    var set = entitySet.AsQueryable();
    var includes = Includes.Instance.Get<T>().DirectCast<Expression<Func<T, object>>[]>();
    if (includes != null)
    {
        foreach (var include in includes)
        {
            set = set.Include(include);
        }
    }
    return set;
}

并按如下方式使用:

public T GetById(int id)
{
    return GetEntitySet().SingleOrDefault(x => x.Id == id);
}