如何将 'Sql in' 与 ASP.NET MVC 存储库模式一起使用
How to use 'Sql in' with ASP.NET MVC repository pattern
我有这个 SQL 查询:
select *
from press
where compId = 36
and categories in (1, 7, 21);
我尝试以 ASP.NET MVC 存储库模式的格式应用它:
iPressRepository.GetAll().Where(x => (x.compId == 36)).ToList();
但我的结果不正确,因为我在第二个查询中错过了类别 'in'。有没有办法使用存储库模式应用 IN
运算符?
提前致谢
我想应该是这样的
iPressRepository.GetAll().Where(x => (x.compId == 36)&&(x.categories==1||x.categories==7||x.categories==21)).ToList();
var categoriesToLookFor = new[] { 1, 7, 21 };
var press = iPressRepository.GetAll()
.Where(x => (x.compId == 36) && (categoriesToLookFor.Contains(x.categories)))
.ToList();
如果您使用 GetAll(),您将从 SQL 获取所有数据,但您只需要一些数据,因此您应该使用 AsQueryable()
存储库:
public IQueryable<T> AsQueryable()
{
return _entities.AsQueryable();
}
控制器:
var list = iPressRepository.AsQueryable()
.Where(i => (new[] { 1, 7, 21 }).Contains(i.categories) && i.compId == 36).ToList();
我有这个 SQL 查询:
select *
from press
where compId = 36
and categories in (1, 7, 21);
我尝试以 ASP.NET MVC 存储库模式的格式应用它:
iPressRepository.GetAll().Where(x => (x.compId == 36)).ToList();
但我的结果不正确,因为我在第二个查询中错过了类别 'in'。有没有办法使用存储库模式应用 IN
运算符?
提前致谢
我想应该是这样的
iPressRepository.GetAll().Where(x => (x.compId == 36)&&(x.categories==1||x.categories==7||x.categories==21)).ToList();
var categoriesToLookFor = new[] { 1, 7, 21 };
var press = iPressRepository.GetAll()
.Where(x => (x.compId == 36) && (categoriesToLookFor.Contains(x.categories)))
.ToList();
如果您使用 GetAll(),您将从 SQL 获取所有数据,但您只需要一些数据,因此您应该使用 AsQueryable()
存储库:
public IQueryable<T> AsQueryable()
{
return _entities.AsQueryable();
}
控制器:
var list = iPressRepository.AsQueryable()
.Where(i => (new[] { 1, 7, 21 }).Contains(i.categories) && i.compId == 36).ToList();