![](/img/trans.png)
[英]How do I query a SQL Server database with a list of parameters in Dapper?
[英]Dapper query with list of parameters
我正在嘗試使用具有已知參數集的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可以在進行批量插入和更新時處理參數列表,但是不能對選擇執行此操作嗎?
嘗試這個:
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});
啊,我想我明白你的意思了...
是的,有一個情況下,我們支持Execute
不支持,對於查詢,具體是:用各種不同的參數值的順序執行相同的操作。 這對於Execute
很有意義,但對於查詢,可能意味着您應該使用in
來查看其他查詢。 或者,只需循環並連接。
取而代之的是,它正在查看單個參數對象並在尋找公共值-可枚舉對象沒有適用於dapper的任何合適的參數值。
我知道我參加這個聚會已經很晚了,但是,我想我理解這個要求意味着您只想傳遞一些屬性並基於這些動態屬性生成查詢。
使用下面的代碼,我可以使用任何類型,然后填充並傳入具有幾個值集的該類型的對象(我將此稱為我的查詢對象),然后將生成查詢以查找與以下值匹配的對象您在查詢對象中設置。
*請注意布爾值和具有默認值的內容。
動態查詢示例
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
然后它會吐出與上述查詢匹配的所有“域”。
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.
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.