在Dapper中用空值排除参数的函数或方法

时间:2016-08-04 10:37:15

标签: c# sql dapper

我想传递三个值并根据使用Dapper获取结果,但该类中的其他属性自动取空值,我想忽略这些参数。 现在我只是传递说param1并试图获得结果。但是我的对象是param2和param3

connection.Query<T>("Query statement", whereConditions)

whereConditions是param1,param2和param3的对象。但是结果使用来自param的where子句,它具有值并忽略空值

[UPDATE]

查询

select ID, UserName, Screen, Url, LogAction from LogTable 
Where UserName = 'Joe' and Screen = 'edit' and LogAction = 'delete'

现在,从用户界面来看,我不确定是否会收到用户名或屏幕或操作。我可以得到这三个中的任何一个。我的查询必须相应更改

如果我创建匿名对象

var whereConditions = new { UserName = "Joe", Screen = "edit" }

效果很好但是在另一个参数的情况下我需要将其作为

传递
var whereConditions = new { UserName = "Joe", Screen = "edit", LogAction = "save" }

所以我需要了解如何将匿名对象作为条件传递。

希望这个帮助

1 个答案:

答案 0 :(得分:0)

一种简单的方法(只有在始终可以忽略空白条件值时才会起作用,这种情况通常是这些值来自UI表单的情况)将始终传递所有三个参数,但是要构造一个跳过的WHERE子句空白值 - 例如。

select ID, UserName, Screen, Url, LogAction
from LogTable
Where (@UserName = '' or UserName = @UserName)
and (@Screen = '' or Screen = @Screen)
and (@LogAction = '' or LogAction = @LogAction)

然后你将传递所有三个值,无论它们是否为空/空白

return conn.Query<Result>(
    @"
        select ID, UserName, Screen, Url, LogAction
        from LogTable
        Where (@UserName = '' or UserName = @UserName)
        and (@Screen = '' or Screen = @Screen)
        and (@LogAction = '' or LogAction = @LogAction)
    ",
    new
    {
        UserName = userName?? "",
        Screen = screen ?? "",
        LogAction = logAction ?? ""
    }
);

如果你把它包装在带有可选参数的方法中,例如:

private IEnumerable<Result> GetData(
    string userName = null,
    string screen = null,
    string logAction = null)
{
    using (var conn = GetConnection())
    {
        return conn.Query<Result>(
            @"
                select ID, UserName, Screen, Url, LogAction
                from LogTable
                Where (@UserName = '' or UserName = @UserName)
                and (@Screen = '' or Screen = @Screen)
                and (@LogAction = '' or LogAction = @LogAction)
            ",
            new
            {
                UserName = userName ?? "",
                Screen = screen ?? "",
                LogAction = logAction ?? ""
            }
        );
    }
}

然后你可以让调用代码对于不同数量的参数看起来很自然 - 例如。

var joeData = GetData(userName: "Joe");
var joeEditData = GetData(userName: "Joe", screen: "save");

但是,如果您请求始终具有三个值(userName,screen和logAction),并且您只想忽略null /空值,那么您当然可以简单地调用

var data = GetData(request.UserName, request.Screen, request.LogAction);