通用存储库和实体框架: 我打算使用通用存储库来处理上下文的查询,并注意到(使用SQL服务器分析器)过滤器表达式没有被翻译并包含在对数据库的SQL查询中。只是想知道在使用通用存储库时是否会出现这种过载? 存储库代码:
public class BaseRepositories<TEntity> where TEntity : class
{
private readonly DbContext _CurrentObjectContext;
private readonly DbSet<TEntity> _EntityObjectSet;
public BaseRepositories(DbContext currentObjectContext)
{
_CurrentObjectContext = currentObjectContext;
_EntityObjectSet = _CurrentObjectContext.Set<TEntity>();
}
public DbSet<TEntity> EntityObjectSet
{
get
{
return _EntityObjectSet;
}
}
public IQueryable<TEntity> Query(Func<TEntity, bool> expression, params Expression<Func<TEntity, object>>[] navigationProperties)
{
var ReturnSetQueryable = _EntityObjectSet.Where(expression);
return ReturnSetQueryable.AsQueryable();
}
}
从资源管理器调用存储库和上下文以及SQL查询 a)使用存储库:
代码:
var UserRepository = new BaseRepositories<user>(new DbContext());
var UsersQuery = UserRepository.Query(v => v.name == "ajayr");
var FirstUser = UsersQuery.FirstOrDefault();
从Sql Profiler查询:
选择 [Extent1]。[guid] AS [guid], [Extent1]。[id] AS [id], [Extent1]。[name] AS [name], [Extent1]。[密码] AS [密码], [Extent1]。[first_name] AS [first_name], [Extent1]。[middle_name] AS [middle_name], [Extent1]。[last_name] AS [last_name], [Extent1]。[email_address] AS [email_address], [Extent1]。[url] AS [url], [Extent1]。[account_enabled] AS [account_enabled], [Extent1]。[user_id] AS [user_id], [Extent1]。[last_update] AS [last_update], [Extent1]。[删除] AS [删除], [Extent1]。[employee_id] AS [employee_id], [Extent1]。[rec_source] AS [rec_source], [Extent1]。[last_login_date] AS [last_login_date], [Extent1]。[last_email_update] AS [last_email_update], [Extent1]。[invalid_email_adr] AS [invalid_email_adr] FROM [dbo]。[users] AS [Extent1]
b)对上下文的直接查询:
代码:
DbContext db = new DbContext();
DbSet<user> usersset = db.Set<user>();
var UserQueryWithFilter = usersset.Where(v => v.name == "ajayr");
var FirstUser = tesst.FirstOrDefault();
从Sql Profiler查询:
SELECT TOP(1) [Extent1]。[guid] AS [guid], [Extent1]。[id] AS [id], [Extent1]。[name] AS [name], [Extent1]。[密码] AS [密码], [Extent1]。[first_name] AS [first_name], [Extent1]。[middle_name] AS [middle_name], [Extent1]。[last_name] AS [last_name], [Extent1]。[email_address] AS [email_address], [Extent1]。[url] AS [url], [Extent1]。[account_enabled] AS [account_enabled], [Extent1]。[user_id] AS [user_id], [Extent1]。[last_update] AS [last_update], [Extent1]。[删除] AS [删除], [Extent1]。[employee_id] AS [employee_id], [Extent1]。[rec_source] AS [rec_source], [Extent1]。[last_login_date] AS [last_login_date], [Extent1]。[last_email_update] AS [last_email_update], [Extent1]。[invalid_email_adr] AS [invalid_email_adr] FROM [dbo]。[用户] AS [Extent1] 在哪里'ajayr'= [Extent1]。[name]
答案 0 :(得分:1)
您提供的是函数,而不是表达式作为参数。我认为您需要稍微更改语法
public IQueryable<TEntity> Query(Expression<Func<TEntity, bool>> expression, params Expression<Func<TEntity, object>>[] navigationProperties)
{
var ReturnSetQueryable = _EntityObjectSet.Where(expression);
return ReturnSetQueryable.AsQueryable();
}