Uma*_*haq 2 c# entity-framework repository-pattern entity-framework-4.1
在开发数据访问解决方案时,该解决方案利用实体框架 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();
}
}
Run Code Online (Sandbox Code Playgroud)
其中 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;
}
Run Code Online (Sandbox Code Playgroud)
DbContext 类将 IDbContext 实现为:
public partial class MyEntities : IDbContext
{
public DbSet<T> GetDbSet<T>() where T : class
{
return this.Set<T>();
}
}
Run Code Online (Sandbox Code Playgroud)
当我执行 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-842be6f6e5ed 和 EF DbContext.Set<T> 仅过滤记录
这些线程证实了我的思考过程,但结果不同。任何解决方案?
谢谢。
您的谓词是 a Func<T, bool>,它强制查询使用Enumerable.Where方法而不是Queryable.Where方法。
将谓词更改为Expression<Func<T, bool>>,一切都应该开始工作。
| 归档时间: |
|
| 查看次数: |
1033 次 |
| 最近记录: |