[英]How can I execute this sql statement with .NET and Dapper.NET?
I have the following sql query: 我有以下sql查询:
BEGIN TRAN;
UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = xxx;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', xxx);
ROLLBACK TRAN;
and this is for a list of id's. 这是一个id的列表。 eg. 例如。
var fooIds = new [] { 1, 2, 3, 4, 5, 6 };
so then I expect this.. 所以我希望这个......
BEGIN TRAN;
UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = 1;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', 1);
UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = 2;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', 2);
UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = 3;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', 3);
ROLLBACK TRAN;
Can this be done with Dapper ? 这可以用Dapper完成吗?
NOTE: If the TRAN
makes this hard, I can drop that. 注意:如果TRAN
使这很难,我可以放弃它。
Dapper has only minimal support for altering queries internally (it supports list expansion for IN
, literal injection, and some OPTION
/ UNKNOWN
tweaks. You have two options here: Dapper对内部更改查询的支持很少(它支持IN
列表扩展,文字注入和一些OPTION
/ UNKNOWN
调整。这里有两个选项:
StringBuilder
to create a single large operation that you can execute (this can be parameterized via a dictionary) 使用StringBuilder
创建一个可以执行的大型操作(可以通过字典进行参数化) For the latter, perhaps something like: 对于后者,可能是这样的:
using(var tran = conn.BeginTransaction())
{
try
{
conn.Execute(@"
UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = @id;
INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', @id);",
fooIds.Select(id => new { id }), transaction: tran);
}
finally // in this example, we always want to rollback
{
tran.Rollback();
}
}
you can do something like this: 你可以这样做:
using (var connection = new SqlConnection(yourConnectionString))
{
connection.Open();
using (var tx = connection.BeginTransaction())
{
foreach (var fooId in fooIds)
{
connection.Execute("UPDATE [dbo].[Foo] SET StatusType = 2 WHERE FooId = @id; INSERT INTO [dbo].[FooNotes] (FooId, Note) VALUES ('blah....', @id);", new {id = fooId}, tx);
}
tx.Rollback();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.