14

我正在尝试使用具有一组已知参数的 Dapper 运行查询,但使用这些参数的值列表。我正在尝试做的一个简单示例是:

DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddHours(-24);

string query = "select COUNT(*) from Test where Status = @Status AND DateCreated <= @Hour;";
var stuff = con.Query(query, (startDate).ByHourTo(endDate).Select(hour => new
{
     Status = 1,
     Hour = hour,
}));

Dapper 抛出异常,“必须定义参数 '@Status'”。我知道 Dapper 在进行批量插入和更新时可以处理参数列表,但它不能对选择执行此操作吗?

4

4 回答 4

24

试试这个:

List<string> names = new List<string> { "Bob", "Fred", "Jack" };
string query = "select * from people where Name in @names";
var stuff = connection.Query<ExtractionRecord>(query, new {names});
于 2012-11-08T15:08:05.280 回答
9

啊,我想我明白你的意思了……

是的,我们支持的一种场景Execute是 Query 不支持的,特别是:使用一系列不同的参数值顺序运行相同的操作。这对于 是有意义的Execute,但对于查询,它可能意味着您应该使用 . 查看不同的查询in。或者,只需循环和连接。

相反,它正在查看单个参数对象并寻找公共值 - 可枚举没有任何适合 dapper 的参数值。

于 2012-11-08T16:46:09.530 回答
3

我知道我参加这个聚会已经很晚了,但是我想我理解这个请求意味着您只想传递一些属性并根据这些动态属性生成您的查询。

使用下面的代码,我可以使用任何类型,然后只需填充并传入一个设置了一些值的类型的对象(我称之为我的查询对象),然后将生成查询以查找与以下值匹配的对象您在查询对象中设置。

*注意布尔值和具有默认值的东西。

动态查询示例

    public IEnumerable<T> Query<T>(T templateobject) {
        var sql = "SELECT * From " + typeof(T).Name + " Where ";

        var list = templateobject.GetType().GetProperties()
             .Where(p => p.GetValue(templateobject) != null)
             .ToList();

        int i = 0;

        Dictionary<string, object> dbArgs = new Dictionary<string, object>();

        list.ForEach(x =>
        {
            sql += x.Name + " = @" +  x.Name;

            dbArgs.Add(x.Name, x.GetValue(templateobject));

            if (list.Count > 1 && i < list.Count - 1) {
                sql += " AND ";
                i++;
            }
        });

        Debug.WriteLine(sql);

        return _con.Query<T>(sql, dbArgs).ToList();
    }

用法

*repo 是包含上述函数的类

var blah = repo.Query<Domain>(new Domain() { Id = 1, IsActive=true });

输出

SELECT * From Domain Where Id = @Id AND IsActive = @IsActive

然后它会吐出与上述查询匹配的任何“域”。

于 2015-12-11T19:16:14.230 回答
0
DECLARE @Now datetime
SET @Now = getdate()

SELECT
    DATEADD( hh, -n, @Now ) AS StartDate,
    DATEADD( hh, -n+1, @Now ) AS EndDate
INTO
    #DateRanges
FROM 
    Numbers
WHERE
    n <= 24

SELECT
    COUNT(*) AS [Count],
    #DateRanges.StartDate
FROM
    Test
        JOIN
    #DateRanges
        ON Test.DateCreated >= #DateRanges.StartDate
        AND Test.DateCreated < #DateRanges.EndDate
GROUP BY
    #DateRanges.StartDate

我就是这样做的,但这假设一件事:您的数据库中有一个名为“Numbers”的表,其中包含任意数量的整数,每行一个,从 1 开始,其中至少有 24 个数字。

也就是说,表格如下所示:

n
-----
1
2
3
4
5
...

如果你没有这样的表,那么只为这个命令制作一个非常快速和容易:

CREATE TABLE #Numbers
(
    n int
)

SET NOCOUNT ON

INSERT #Numbers values (1);
GO
INSERT #Numbers SELECT n + (SELECT COUNT(*) FROM #Numbers) FROM #Numbers
GO 16 --execute batch 16 times to create 2^16 integers.

存储过程中不能有多个批次,但可以在文本命令中。GO 16运行前一批 16 次。如果您在存储过程中需要这个,您可以INSERT多次重复第二个命令,而不是使用批处理。2^16 整数对于这个特定的查询来说太过分了,但它是我在需要时复制和粘贴的命令,而且 2^16 通常就足够了,而且速度如此之快,以至于我通常不会费心去改变它。GO 5将产生 32 个整数,足以满足 24 个日期范围。

这是一个完整的脚本来说明这个工作:

--Create a temp table full of integers. This could also be a static 
--table in your DB. It's very handy.
--The table drops let us run this whole script multiple times in SSMS without issue.
IF OBJECT_ID( 'tempdb..#Numbers' ) IS NOT NULL
    DROP TABLE #Numbers

CREATE TABLE #Numbers
(
    n int
)

SET NOCOUNT ON

INSERT #Numbers values (1);
GO
INSERT #Numbers SELECT n + (SELECT COUNT(*) FROM #Numbers) FROM #Numbers
GO 16 --execute batch 16 times to create 2^16 integers.

--Create our Test table. This would be the real table in your DB, 
-- so this would not go into your SQL command.
IF OBJECT_ID( 'tempdb..#Test' ) IS NOT NULL
    DROP TABLE #Test

CREATE TABLE #Test
(
    [Status] int,
    DateCreated datetime
)

INSERT INTO 
    #Test 
SELECT 
    1, 
    DATEADD( hh, -n, getdate() )
FROM 
    #Numbers
WHERE
    n <= 48

--#Test now has 48 records in it with one record per hour for 
--the last 48 hours.

--This drop would not be needed in your actual command, but I 
--add it here to make testing this script easier in SSMS.
IF OBJECT_ID( 'tempdb..#DateRanges' ) IS NOT NULL
    DROP TABLE #DateRanges

--Everything that follows is what would be in your SQL you send through Dapper 
--if you used a static Numbers table, or you might also want to include
--the creation of the #Numbers temp table.
DECLARE @Now datetime
SET @Now = getdate()

SELECT
    DATEADD( hh, -n, @Now ) AS StartDate,
    DATEADD( hh, -n+1, @Now ) AS EndDate
INTO
    #DateRanges
FROM 
    #Numbers
WHERE
    n <= 24

/* #DateRanges now contains 24 rows that look like this:

StartDate               EndDate
2016-08-04 15:22:26.223 2016-08-04 16:22:26.223
2016-08-04 14:22:26.223 2016-08-04 15:22:26.223
2016-08-04 13:22:26.223 2016-08-04 14:22:26.223
2016-08-04 12:22:26.223 2016-08-04 13:22:26.223
...

Script was run at 2016-08-04 16:22:26.223. The first row's end date is that time. 
This table expresses 24 one-hour datetime ranges ending at the current time. 
It's also  easy to make 24 one-hour ranges for one calendar day, or anything
similar.
*/

--Now we just join that table to our #Test table to group the rows those date ranges.

SELECT
    COUNT(*) AS [Count],
    #DateRanges.StartDate
FROM
    #Test
        JOIN
    #DateRanges
        ON #Test.DateCreated >= #DateRanges.StartDate
        AND #Test.DateCreated < #DateRanges.EndDate
GROUP BY
    #DateRanges.StartDate

/*
Since we used two different getdate() calls to populate our two tables, the last record of 
our #Test table is outside of the range of our #DateRange's last row by a few milliseconds,
so we only get 23 results from this query. This script is just an illustration.
*/
于 2016-08-04T20:59:40.963 回答