【问题标题】:Is it possible to do this build this query with Dapper?是否可以使用 Dapper 构建此查询?
【发布时间】:2015-05-23 07:07:23
【问题描述】:

是否可以执行以下操作?我试过了,但是当它到达查询时,它只是说有一个空引用。

   var builder = new StringBuilder("select * from my table1 where 1 = 1");

if(x==1)
    builder.Append(" and x = @x");

if(y==2)
    builder.Append(" and y = @y");

// when it gets here, it just says null reference

 db.Query<table1>(builder.ToString(), new {x,y});

我让 SqlBuilder 在 .net 3.5 中运行,但是当我这样做时:

var builder = new SqlBuilder();

var sql = builder.AddTemplate("select * from table /**where**/ /**orderby**/");

 builder.Where("a = @a", new { a = 1 })
        .OrWhere("b = @b", new { b = 2 });

我期待select * from table WHERE a = @a OR ( b = @b )

但我得到了:

我期待select * from table WHERE a = @a AND ( b = @b )

【问题讨论】:

  • 请引用整个错误信息。
  • 我没有立即看到任何错误;你有异常的堆栈跟踪吗?
  • @MarcGravell - 抱歉,Marc,我最初是在手机上输入的,没有原始错误消息。如果 x 和 y 不为空或 null,它可以工作,但如果我只指定其中一个,它会引发错误。我正在使用 .NET 3.5 的 SqlMapper。
  • 嗯,这不是我见过的东西。我可以看,但是堆栈跟踪确实会有所帮助
  • 你确定 db 是非空的吗?

标签: c# .net-3.5 dapper


【解决方案1】:

大概是因为this bug。尝试的修复是在 2016 年 7 月 31 日进行的,但是 there are still issues 使用这种方法。计划是在下一个主要版本中修复此问题。

【讨论】:

    【解决方案2】:

    您可以使用DapperQueryBuilder轻松创建动态条件:

    var query = cn.QueryBuilder($@"
        SELECT * 
        FROM Table
        WHERE 1=1
    ");
    
    if(x==1)
        query.Append($"and x = {x}");
    
    if(y==2)
        builder.Append($" and y = {y}");
    
    var results = query.Query<YourPOCO>();
    

    输出是完全参数化的 SQL (WHERE 1=1 AND x = @p0 AND y = @p1)。

    免责声明:我是这个库的作者之一

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2017-08-05
      • 2017-08-14
      相关资源
      最近更新 更多