![](/img/trans.png)
[英]Parameter not provided to the stored procedure when I use Dapper DynamicParameter from C# dictionary
[英]C# remove SQL from method and use stored procedure & Dapper
我正在嘗試將一種方法轉換為與Dapper一起使用存儲過程。 但是我對var result =...
public Task<TUser> FindByIdAsync(Guid userId)
{
var sql = @"SELECT *
FROM IdentityUser
WHERE UserId = @USERID";
using (var connection = new SqlConnection(_connection))
{
var result = connection.Query<TUser, IdentityProfile, TUser>(sql, (user, profile) => { user.Profile = profile;
return user; },
new { userId }, splitOn: "UserId").SingleOrDefault();
return Task.FromResult(result);
}
}
這是我所擁有的:
public Task<TUser> FindByIdAsync(Guid userId)
{
using (var connection = new SqlConnection(_connection))
{
var param = new DynamicParameters();
param.Add("@UserId", userId);
return Task.FromResult(connection.Query("IdentityGetUserById", param, commandType: CommandType.StoredProcedure).SingleOrDefault());
}
}
但是我對var result = ...
不必混淆,這是簡單的Dapper功能
讓我解釋一下以下代碼的作用:
var result = connection.Query<TUser, IdentityProfile, TUser>
(sql, (user, profile) =>
{
user.Profile = profile;
return user;
}, new { userId },
splitOn: "UserId").SingleOrDefault();
UserId
處拆分,然后代表配置文件類型,根據邏輯user.Profile = profile
將其填充到用戶類型中user.Profile = profile
IEnumerable<TUser>
,因此將調用SingleOrDefault
,如果返回Single record
或返回null
,它將返回數據 complex types
的標准機制 現在,當您運行存儲過程IdentityGetUserById
,需要使用相同類型的代碼,只有更改是用存儲過程名稱(完成)替換實際的Sql,告訴Dapper您正在執行存儲過程(完成),您已經使用DynamicParameter
綁定了參數,也可以是匿名類型。 結果將采用類似的格式,您可以進行完全相同的綁定,請檢查以下代碼,並進行少量修改:
using (var connection = new SqlConnection(_connection))
{
var result = connection.Query<TUser, IdentityProfile, TUser>
("IdentityGetUserById",
commandType: CommandType.StoredProcedure,
(user, profile) =>
{
user.Profile = profile;
return user;
}, new { userId },
splitOn: "UserId").SingleOrDefault();
return Task.FromResult(result);
);
}
實際上,我已經刪除了Dynamic Parameters
並使用了Anonymous type
來確保它與Sql代碼一致
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.