儲存過程
簡單的用法
Dapper 完全支援儲存過程:
var user = conn.Query<User>("spGetUser", new { Id = 1 },
commandType: CommandType.StoredProcedure)
.SingleOrDefault();
輸入,輸出和返回引數
如果你想要更有趣的東西,你可以這樣做:
var p = new DynamicParameters();
p.Add("@a", 11);
p.Add("@b",
dbType: DbType.Int32,
direction: ParameterDirection.Output);
p.Add("@c",
dbType: DbType.Int32,
direction: ParameterDirection.ReturnValue);
conn.Execute("spMagicProc", p,
commandType: CommandType.StoredProcedure);
var b = p.Get<int>("@b");
var c = p.Get<int>("@c");
表值引數
如果你有一個接受表值引數的儲存過程,則需要傳遞一個 DataTable,它具有與 SQL Server 中的表型別相同的結構。這是一個使用它的表型別和過程的定義:
CREATE TYPE [dbo].[myUDTT] AS TABLE([i1] [int] NOT NULL);
GO
CREATE PROCEDURE myProc(@data dbo.myUDTT readonly) AS
SELECT i1 FROM @data;
GO
/*
-- optionally grant permissions as needed, depending on the user you execute this with.
-- Especially the GRANT EXECUTE ON TYPE is often overlooked and can cause problems if omitted.
GRANT EXECUTE ON TYPE::[dbo].[myUDTT] TO [user];
GRANT EXECUTE ON dbo.myProc TO [user];
GO
*/
要從 C#中呼叫該過程,你需要執行以下操作:
// Build a DataTable with one int column
DataTable data = new DataTable();
data.Columns.Add("i1", typeof(int));
// Add two rows
data.Rows.Add(1);
data.Rows.Add(2);
var q = conn.Query("myProc", new {data}, commandType: CommandType.StoredProcedure);