c# - 使用 Dapper 将项目列表(可能为空)作为 IN 子句的参数传递

标签 c# sql sql-server sql-server-2008 dapper

尝试使用 Dapper 将 NULL 项目列表作为参数传递时,出现 NULL 引用异常。通常在我的 where 子句中,我会简单地执行以下操作:

"AND (@Sections IS NULL OR Section IN @Sections)";

但我无法执行此操作,因为即使部分列表中有项目,它也不会工作。 Dapper 将它们添加为参数并且 (@sections1,@sections2 IS NULL OR) 将出错。如果我将我的部分列表保留为空,因为我不想将它用作过滤器,我会得到 NULL 引用异常。

我的函数必须有一个部分列表作为可选参数。这样,在我的代码中,我不必总是向我的查询添加部分过滤器。如何在我的函数参数中使部分成为可为 null 的列表,同时在 NULL 时也能与 Dapper 一起工作?

这是我的代码:

public static IEnumerable<Product> GetProformaFormularies(int? categoryId = null, IEnumerable<int> sections = null)
{
    using (var context = new AppContext())
    {
        var sql =
        "SELECT * " +
        "FROM Products " +
        "WHERE (@CategoryId IS NULL OR CategoryId = @CategoryId) " +
          "AND (Section IN @Sections)";

        return context.Database.Connection.Query<Product>(sql, 
        new { 
                CategoryId = categoryId,
                Sections = sections
            }).ToList();
    }
}

我想到的唯一解决方案是使用动态参数。还有比这更好的方法吗?

var sql =
    "SELECT * " +
    "FROM ProformaFormulary " +
    "WHERE (@CategoryId IS NULL OR CategoryId = @CategoryId) " +

if (sections != null)
{
    sql += " AND (Section IN @Sections)";
}

var parameters = new DynamicParameters();
parameters.Add("@CategoryId", categoryId);
if (sections != null)
{
    parameters.Add("@Sections", sections);
}

最佳答案

如果 sectionsnull,您可以省略 WHERE 子句的那部分:

var sql =
    "SELECT * " +
    "FROM Products " +
    "WHERE (@CategoryId IS NULL OR CategoryId = @CategoryId) ";

if (sections != null)
{
    sql += "AND (Section IN @Sections)"
}

return context.Database.Connection.Query<Product>(sql, 
    new { 
            CategoryId = categoryId,
            Sections = sections
        }).ToList();

看起来 dapper 将忽略您传递的对象的 Sections 属性,如果它不适用的话。

关于c# - 使用 Dapper 将项目列表(可能为空)作为 IN 子句的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870911/

相关文章:

c# - 将 gridview 值显示到文本框中

mysql - 如何将多个 Rails SQL 查询合并到 Rails 中的单个查询中?

SQL Server 对单个列进行多次拆分

c# - 参数类型 'Edm.String' 和 'Edm.Int32' 与此操作不兼容

c# - 在保存到 redis 之前压缩对象

c# - 拆分重叠日期范围的最快方法

c# - 从内部派生的公共(public)接口(interface)?

c# - SQL 语句 - 如何编写带有通配符的 WHERE 子句

java - 数据未插入 SQLite 数据库

sql-server - 使用变量转换数据类型