可空的十进制字段的Dapper查询不起作用

时间:2016-08-23 07:23:01

标签: c# orm dapper

我有一个包含可空小数(12,4)列的表。当我这样查询时:

const string sqlQuery = "SELECT Id From DummyTable WHERE Price = @Price";

var sqlParameter = new { Price = (decimal?)null };

此查询返回0记录。但是当我将查询更改为:

const string sqlQuery = "SELECT Id From DummyTable WHERE Price IS NULL;

这种语法有效。那么如何用参数查询可空的十进制列呢?感谢。

1 个答案:

答案 0 :(得分:1)

它不是很性感,但你可以尝试这样的事情:

[Test]
public void NullParamTest()
{
    _connection.Execute(@"drop table foo; 
                          create table foo(id int not null,price decimal(12, 4) null)");
    _connection.Execute("insert into foo values(1, null)");
    _connection.Execute("insert into foo values(2, 12.99)");

    const string sql = @"select price from foo 
                        where coalesce(price, -1) = coalesce(@Price, -1)";

    var result = _connection.Query<decimal?>(sql,new { Price = (decimal?)null }).FirstOrDefault();
    Assert.That(result, Is.Null);

    result = _connection.Query<decimal?>(sql,new { Price = 12.99 }).FirstOrDefault();
    Assert.That(result, Is.EqualTo(12.99));
}

假设&#34;价格&#34;不能否定......