学海无涯

导航

Dapper 传递参数

 [HttpGet("QueryByAnonymousType")]
        public async Task<ActionResult<IEnumerable<Product>>> QueryByAnonymousType()
        {//参数作为匿名类型
            var parameters = new { ProductName = "Ikura", UnitPrice = 31 };
            //或者 var parameters = new Product{ ProductName = "Ikura", UnitPrice = 31 };
            var sql = "select * from Products Where ProductName=@ProductName and UnitPrice=@UnitPrice";
            using (var con = new SqlConnection(MyConfig.ConnectionString))
            {
                var result = await con.QueryAsync(sql, parameters);
                return Ok(result);
            }
        }
        //动态参数包
        [Route("QueryByDynamicParameters")]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Product>>> QueryByDynamicParameters()
        {//Dapper 还提供了一个DynamicParameters类,它表示参数值的“包”。
         //您可以将对象传递给它的构造函数。合适的对象包括Dictionary<string, object>:
            var dictionary = new Dictionary<string, object>
            {
                {"@ProductId",1 }
            };
            var parameters = new DynamicParameters(dictionary);
            var sql = "select * from products where ProductId=@ProductId";
            using (var con = new SqlConnection(MyConfig.ConnectionString))
            {
                var products = await con.QuerySingleAsync<Product>(sql, parameters);
                return Ok(products);
            }
        }
        [Route("QueryByAddParameters")]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Customer>>> QueryByAddParameters()
        {//该DynamicParameters类型提供了一种Add方法,使您能够传递显式参数,指定数据类型、方向和大小:
            var parameters = new DynamicParameters();
            var customerId = "ALFKI";
            parameters.Add("@CustomerId", customerId, DbType.String, ParameterDirection.Input, customerId.Length);
            var sql = "select * from customers where CustomerId=@customerId";
            using (var con = new SqlConnection(MyConfig.ConnectionString))
            {
                var customers = await con.QuerySingleAsync<Customer>(sql, parameters);
                return Ok(customers);
            }
        }

  

posted on 2022-10-04 14:56  宁静致远.  阅读(465)  评论(0编辑  收藏  举报