Dapper官方教程翻译9:Dapper方法之参数类型
1.匿名参数(常用)
单个查询:
- string sql = "INSERT INTO Customers (CustomerName) Values (@CustomerName);";
-
- using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
- {
- var affectedRows = connection.Execute(sql, new {CustomerName = "Mark"});
-
- Console.WriteLine(affectedRows);
-
- // Only for see the Insert.
- var customer = connection.Query<Customer>("Select * FROM CUSTOMERS WHERE CustomerName = 'Mark'").ToList();
-
- FiddleHelper.WriteTable(customer);
- }
批量查询:
- string sql = "INSERT INTO Customers (CustomerName) Values (@CustomerName);";
-
- using (var connection = new SqlCeConnection("Data Source=SqlCe_W3Schools.sdf"))
- {
- var affectedRows = connection.Execute(sql,
- new[]
- {
- new {CustomerName = "John"},
- new {CustomerName = "Andy"},
- new {CustomerName = "Allan"}
- }
-
- Console.WriteLine(affectedRows);
- )
2.动态参数(常用于存储过程)
单个操作:
- var sql = "EXEC Invoice_Insert";
-
- using (var connection = My.ConnectionFactory())
- {
- connection.Open();
-
- DynamicParameters parameter = new DynamicParameters();
-
- parameter.Add( "@Kind", InvoiceKind.WebInvoice, DbType.Int32, ParameterDirection.Input);
- parameter.Add( "@Code", "Many_Insert_0", DbType.String, ParameterDirection.Input);
- parameter.Add( "@RowCount", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
-
- connection.Execute(sql,
- parameter,
- commandType: CommandType.StoredProcedure);
-
- int rowCount = parameter.Get<int>("@RowCount");
- }
批量操作:
- var sql = "EXEC Invoice_Insert";
-
- var parameters = new List<DynamicParameters>();
-
- for (var i = 0; i < 3; i++)
- {
- var p = new DynamicParameters();
- p.Add( "@Kind", InvoiceKind.WebInvoice, DbType.Int32, ParameterDirection.Input);
- p.Add( "@Code", "Many_Insert_" + (i + 1), DbType.String, ParameterDirection.Input);
- p.Add( "@RowCount", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
-
- parameters.Add(p);
- }
-
- using (var connection = My.ConnectionFactory())
- {
- connection.Open();
-
- connection.Execute(sql,
- parameters,
- commandType: CommandType.StoredProcedure
- );
-
- var rowCount = parameters.Sum(x => x.Get<int>("@RowCount"));
- }
3.列表参数
- var sql = "SELECT * FROM Invoice WHERE Kind IN @Kind;";
-
- using (var connection = My.ConnectionFactory())
- {
- connection.Open();
-
- var invoices = connection.Query<Invoice>(sql, new {Kind = new[] {InvoiceKind.StoreInvoice, InvoiceKind.WebInvoice}}).ToList();
- }
4.字符串参数
- var sql = "SELECT * FROM Invoice WHERE Code = @Code;";
-
- using (var connection = My.ConnectionFactory())
- {
- connection.Open();
-
- var invoices = connection.Query<Invoice>(sql, new {Code = new DbString {Value = "Invoice_1", IsFixedLength = false, Length = 9, IsAnsi = true}}).ToList();
-
- My.Result.Show(invoices);
- }