2

在开发利用通用存储库和实体框架 4.2 上的工作单元模式的数据访问解决方案时。我看到一些异常行为。为了使我的存储库通用,我使用了 DbContext 的 Set 方法,例如:

public class MyGenericRepository<T> 
{
     protected readonly IDbContext context;
     public virtual IEnumerable<T> FindBy(Func<T, bool> predicate)
     {
        return context.GetDbSet<T>().Where(predicate).First();
     }
}

IDbContext 就像:

public interface IDbContext
{
    void Commit();
    void Attach<T>(T obj) where T : class;
    void Add<T>(T obj) where T : class;
    DbSet<T> GetDbSet<T>() where T : class;
    bool Remove<T>(T item) where T : class;
}

DbContext 类将 IDbContext 实现为:

public partial class MyEntities : IDbContext
{

    public DbSet<T> GetDbSet<T>() where T : class
    {
        return this.Set<T>();
    }
}  

当我执行 repository.FindBy(c => c.CompanyId == 45) 时,Sql Profiler 显示查询包含任何过滤器(company_id = 45)。该查询执行 Select *。

期待过滤器出现,我开始研究并遇到了这个,

http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/7d6705ac-f875-4c89-960b-842be6f6e5edEF DbContext.Set<T> 仅过滤记录

这些线程证实了我的思考过程,但结果不同。有什么解决办法吗?

谢谢。

4

1 回答 1

5

您的谓词是 a Func<T, bool>,它强制查询使用Enumerable.Where方法而不是Queryable.Where方法。

将谓词更改为Expression<Func<T, bool>>,一切都应该开始工作。

于 2012-11-06T21:04:06.530 回答