Dapper.NET 存储过程
示例
简单使用
Dapper完全支持存储的proc:
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");
表值参数
如果您有一个接受表值参数的存储过程,则需要传递一个数据表,该表的结构与SQLServer中的表类型相同。这是表类型和使用它的过程的定义:
CREATE TYPE [dbo].[myUDTT] AS TABLE([i1] [int] NOT NULL); GO CREATE PROCEDURE myProc(@datadbo.myUDTTreadonly) 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 ONdbo.myProcTO [user]; GO */
要从c#中调用该过程,您需要执行以下操作:
// 用一个int列构建一个DataTable DataTable data = new DataTable(); data.Columns.Add("i1", typeof(int)); // 加两行 data.Rows.Add(1); data.Rows.Add(2); var q = conn.Query("myProc", new {data}, commandType: CommandType.StoredProcedure);