我喜欢使用Dapper来满足我的ORM需求,但我知道必须有一种更好的方法来使用存储过程和强类型列表来插入/更新我的sql server数据库。
例如:
我有一首歌曲:
public class Song
{
public int Id { get; set; }
public string title { get; set; }
public string genre { get; set; }
}
并且有人提交了歌曲列表:
List<Song> songs = new List<Song> {
new Song { Id = 1, title = "Song 1" , genre="rock"},
new Song { Id = 2, title = "Song 2" , genre="disco"}};
我想使用我的存储过程更新数据库,该存储过程会插入新歌曲,或者如果歌曲已经存在则更新它。我的存储过程有两个输出参数:
@success_added int = 0 and @success_updated int = 0
我的sproc如下:
ALTER PROCEDURE [dbo].[UpdateSong]
@Id int = 0,
@title varchar(25) = NULL,
@genre varchar(25) = NULL,
@success_updated bit = 0 OUTPUT,
@success_added bit = 0 OUTPUT
AS
IF NOT EXISTS (SELECT Id FROM Songs WHERE Id = @Id)
BEGIN
INSERT INTO Songs
(
-- Id created by db
title,
genre
)
VALUES
(
@title,
@genre
)
SELECT @Success_Added = 1, @Success_Updated = 0
END
ELSE -- song already exists
BEGIN
UPDATE Songs
SET
title = @title,
@genre = @genre
WHERE Id = @Id
SELECT @Success_Added = 0, @Success_Updated = 1
END
RETURN
我知道这有效:
dbConn.Open();
DynamicParameters p = new DynamicParameters();
foreach (var song in songs)
{
p.Add("@Id", song.Id);
p.Add("@title", song.title);
p.Add("@genre", song.genre);
p.Add("@success_updated", dbType: DbType.Boolean, direction: ParameterDirection.Output);
p.Add("@success_added", dbType: DbType.Boolean, direction: ParameterDirection.Output);
dbConn.Execute("Test_UpdateSong", p, commandType: CommandType.StoredProcedure);
Console.WriteLine("@success_added: " + p.Get<Boolean>("@success_added"));
Console.WriteLine("@success_updated: " + p.Get<Boolean>("@success_updated"));
}
dbConn.Close();
但是这需要手动将每个Song属性转换为匿名类型DynamicParameter。我宁愿这么做:
dbConn.Open();
foreach (var song in songs)
{
var updateResult = dbConn.Query<dynamic>("Test_UpdateSong", song, commandType: CommandType.StoredProcedure);
}
dbConn.Close();
哪个也有效。但是,现在我如何获得输出参数?
答案 0 :(得分:20)
正如我最初所说,我不想手动将每个类属性转换为Dapper动态参数。这很关键,因为如果我创建一个泛型方法,我可能不知道哪个类传递给方法,因此传递哪些属性来转换为动态参数。接受@Metro Smurfs的建议(当所有其他方法都失败时,请阅读指示),我查看了Dapper测试类并找到了适用于我的解决方案:
DynamicParameters p = new DynamicParameters(song);
通过将歌曲对象添加到DynamicParameters构造函数,将创建一个DynamicParameters模板,该模板将自动将所有属性转换为参数。然后我可以简单地添加我的两个输出参数并执行sproc:
p.Add("@success_updated", dbType: DbType.Boolean, direction: ParameterDirection.Output);
p.Add("@success_added", dbType: DbType.Boolean, direction: ParameterDirection.Output);
dbConn.Execute("Test_UpdateSong", p, commandType: CommandType.StoredProcedure);
// get my output parameters...
var success_added = p.Get<bool>("@success_Added");
var success_added = p.Get<bool>("@success_Updated");
我很高兴去!感谢@Nick和@Metro Smurf的建议!