Dapper的语法应用

(1)返回某个整型或字符串类型的字段

public string GetSupplierCodeById(int Id)
{ 
using( var conn=DbFactory.CreateConnection())
{
var result = conn.Query<dynamic>(GetSupplierCodeByIdSql, new { Id = Id }).FirstOrDefault();
return result.Code;
}
}
/// 添加包装
        /// </summary>
        /// <param name="p"></param>
        public int AddPackSP(Pack p)
        {
            using (var conn = DbFactory.CreateConnection())
            {
                //var result = conn.Execute(AddPackSPSql, p);
                var result = conn.Query<dynamic>(AddPackSPSql, p).FirstOrDefault();
                return result != null ? Convert.ToInt32(result.PackId) : 0;
            }
        }

(2)返回一个对象

 public Material GetMaterialByCode(string code)
{
      using (DbConnection conn = DbFactory.CreateConnection())
      {
          var result = conn.Query<Material>(GetMaterialByCodeSql,
          new { Code = code }).FirstOrDefault();
           return result;
       }
 }

(3)返回一个集合

   返回一条数据:

   public IList<Supplier> GetValidSupplier(int employeeId)
        {
            using (var conn = DbFactory.CreateConnection())
            {
                var result = conn.Query<Supplier>(GetValidSupplierByEIdSql,
                  new { EmployeeId = employeeId }).ToList();
                return result;
            }
        }

返回多条数据:

 public IList<Supplier> GetSupplierList(int supplierType)
        {
            using (var conn = DbFactory.CreateConnection())
            {
                var result = conn.QueryMultiple(GetSupplierListBySupplierTypeSql,
                    new { SupplierType = supplierType }).Read<Supplier>().ToList();
                return result;
            }
        }

(4)返回bool类型(判断是否增删改成功或是否被引用等)

 public bool IsUsed(int supplierId)
        {
            using (var conn = DbFactory.CreateConnection())
            {
                var result = conn.QueryMultiple(IsUsedSql,
                    new { SupplierId = supplierId }).Read<int>().Single() > 0;
                return result;
            }
        }
 public bool DeleteMaterial(int materialId)
        {
            using (DbConnection conn = DbFactory.CreateConnection())
            {
                bool result = conn.Execute(DeleteMaterialSql, new { Id = materialId }) > 0;

                return result;
            }
        }

原文地址:https://www.cnblogs.com/abc8023/p/3843339.html