【问题标题】:How to use 'Sql in' with ASP.NET MVC repository pattern如何在 ASP.NET MVC 存储库模式中使用“Sql in”
【发布时间】:2018-09-14 07:04:16
【问题描述】:

我有这个 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 运算符与存储库模式一起应用?

提前致谢

【问题讨论】:

标签: c# sql repository-pattern


【解决方案1】:
var categoriesToLookFor = new[] { 1, 7, 21 };
var press = iPressRepository.GetAll()
                            .Where(x => (x.compId == 36) && (categoriesToLookFor.Contains(x.categories)))
                            .ToList();

【讨论】:

  • 谢谢,但我的 'categoriesToLookFor' 是 int 字段,所以 'int 不包含对.. 的定义,就像那个错误消息
  • “我的categoriesToLookFor”是什么意思?根据您的 SQL 查询,我认为数据库中有问题的列名为 categories
  • 能否请您提供整个错误,并说明哪里出错了?
  • 它工作的兄弟。非常感谢。我的类别字段是 int?(可为空的 int)。然后我把它改成int。然后工作。非常感谢
【解决方案2】:

我认为应该是这样的

iPressRepository.GetAll().Where(x => (x.compId == 36)&&(x.categories==1||x.categories==7||x.categories==21)).ToList();

【讨论】:

  • 这可行,但我的类别是动态的。那么这个查询长度可能会不时变化。谢谢
【解决方案3】:

如果您使用 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();

【讨论】:

    猜你喜欢
    • 2011-04-19
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2012-06-11
    相关资源
    最近更新 更多