【问题标题】:Calling DbContext.Set<T>().Include() is not querying the included properties?调用 DbContext.Set<T>().Include() 不是查询包含的属性吗?
【发布时间】:2012-04-08 01:29:36
【问题描述】:

我在我的 DbContext 上关闭了延迟加载和代理创建。我正在使用存储库合作伙伴和 UnitOfWork。我的 UnitOfWork 继承自 DBConext。这是我正在做的一个例子:

public class User
{
     public Guid Id {get;set;}
     public virtual Guid UserTypeId {get;set;} //foreign key to UserType and setup in the EF fluent mappings and it does load if I am using lazy loading.
     public virtual UserType {get;set;}
}

public class UserType
{
     public Guid Id {get;set;}
     public string Name {get;set;}
}

这是在我的 UoW 里面:

        public IDbSet<TEntity> CreateSet<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }

我通过我的存储库查询上下文:

 protected Expression<Func<TEntity, object>>[] Includes;
 public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> criteria, params Expression<Func<TEntity, object>>[] includes)
        {
            Includes = includes;
            return GetSet().Where(criteria)
                            .AsEnumerable();
        }

    public IDbSet<TEntity> GetSet()
            {
                var set = _unitOfWork.CreateSet<TEntity>();

                if(Includes != null)
                {
                    foreach (var include in Includes)
                    {
                        set.Include(include);
                    }
                }

                return set;

            }

所以,如您所见,我正在传递要包含在查询中的表达式数组。所以我可以这样称呼它:

var users = userRespository.Get(u => u.Id == SomeGuid, u => u.UserType);

UserType 未包含在查询中,我不知道是什么。我应该在 DbContext 上调用 Set 以外的东西吗?

更新

我在调用 base.Set 之前正在考虑我需要在其中添加包含。不过不确定。

【问题讨论】:

  • 如果你使用:set = set.Include(include);会发生什么?
  • @LadislavMrnka,从来没想过......我会试试......
  • @LadislavMrnka,如果你想回答这个问题,我会给你功劳。完美!!!!

标签: entity-framework entity-framework-4.1


【解决方案1】:

IQueryable 上的所有扩展方法通常以它们产生新的IQueryable 的方式工作,因此如果您想获得效果,您必须分配它:

public IDbSet<TEntity> GetSet()
{
    var set = _unitOfWork.CreateSet<TEntity>();

    if(Includes != null)
    {
        foreach (var include in Includes)
        {
            set = set.Include(include);
        }
    }

    return set;
}

顺便说一句。它看起来与my older solution 非常相似。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多