实体框架:通用存储库中的Include和Where子句

时间:2014-04-02 14:02:11

标签: c# sql frameworks repository entity

我使用实体框架(对象上下文)检查通用存储库的可能性。

我有一个界面

    interface IRepository<T> where T : class
    {
       IList<T> GetItems(Func<T, bool> Where, params string[] Navigations);
    }

实现接口的类

    class GenericRepository<T> : IRepository<T> where T : class
    {
       public IList<T> GetItems(Func<T, bool> Where, params string[] Navigations)
       {
           List<T> list;
           using(var ctx = new Context())
           {
               IQueryable<T> query = ctx.CreateObjectSet<T>();

               foreach (string nav in Navigations)
                    (query as ObjectQuery<O>).Include(nav);

               list = query.Where(Where).ToList<T>();
           }
           return list;
       } 
    }

然后我有另一个扩展GenericRepository的类。并实现另一个接口(现在不导入,因为该接口当前只扩展了IRepository而没有添加任何功能)。

    class EmployeeRepository : GenericRepository<Employee>, IEmployeeRepository
    {

    }

当我想从我的存储库中获取数据时,我会这样做:

    private void Test()
    {
        IEmployeeRepository rep = new EmployeeRepository();
        IList<Employee> list = rep.GetItems(
                                            e => e.Department.Name.Contains("Os")
                                            && e.Role.Type == 2,
                                            "Department", "Role"
                                           );
    }

在这里我得到一个错误,说e.Department为null(我相信我也会在角色上得到一个)。

该模型有三个实体

  • 员工
  • 作用

部门1 .. *员工 角色1..1员工

是否可以像我一样在引用表上添加预测? (有一些变化)。

谢谢!

2 个答案:

答案 0 :(得分:6)

首先,使用Expression<Func<T, bool>>代替Func<T, bool>

如果您使用Func<T, bool>,则会在应用谓词之前进行枚举!

这可能已经足够了。

如果不是,请添加一些空检查。

IList<Employee> list = rep.GetItems(
                                     e => e.Department != null && e.Department.Name.Contains("Os")
                                     && e.Role != null && e.Role.Type == 2,
                                     "Department", "Role"
                                    );

最后,我会将GenericRepository的实现更改为

class GenericRepository<T> : IRepository<T> where T : class
    {
       public IList<T> GetItems(Expression<Func<T, bool>> predicate, params string[] navigationProperties)
       {
           List<T> list;
           using(var ctx = new Context())
           {
               var query = ctx.Set<T>().AsQueryable();

               foreach (string navigationProperty in navigationProperties)
                    query = query.Include(navigationProperty);//got to reaffect it.

               list = query.Where(predicate).ToList<T>();
           }
           return list;
       } 
    }

答案 1 :(得分:0)

您确定所有员工都有部门吗?该部门是否已加载? 否则我会添加支票,如果e.Department&lt;&gt;空