C# Dapper 简单实例

///

/// 分页信息
///
public class PageInfo
{
///
/// 分页信息
///
public PageInfo()
{
}
///
/// 总页数
///
public long TotalCount
{
get; set;
}
///
///
///
public IEnumerable Data
{
get; set;
}
///
///
///
///
///
public PageInfo(long total, IEnumerable data)
{
this.TotalCount = total;
this.Data = data;
}
}

*************

using DapperExtensions.Mapper;
using Statistics.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlowStatistics
{
public static class Mappings
{
public static void Initialize()
{
DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>);

DapperExtensions.DapperExtensions.SetMappingAssemblies(new[]
{
typeof(Mappings).Assembly
});
}

public class FlowCellMapper : ClassMapper
{
public FlowCellMapper()
{
Table("jxc_flow_cell");
//Map(fcel => fcel.id).Column("id");
//Map(fcel => fcel.parent_id).Column("parent_id");
//Map(fcel => fcel.create_time).Column("create_time");
//Map(fcel => fcel.type_id).Column("type_id");
Map(fcel => fcel.comId).Column("bloc_code");
//Map(fcel => fcel.bloc_name).Column("bloc_name");
//Map(fcel => fcel.cell_number).Column("cell_number");
//Map(fcel => fcel.name).Column("name");
//Map(fcel => fcel.flows).Column("flows");
//Map(fcel => fcel.status).Column("status");
//Map(fcel => fcel.del).Column("del");
AutoMap();
}
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using DapperExtensions;
using DapperExtensions.Sql;
using MySql.Data.MySqlClient;
using System.Data;
using Z.Dapper.Plus;

namespace FlowStatistics
{
///


/// 数据客户端
/// 参考:https://github.com/StackExchange/dapper-dot-net
/// Predicates参考:https://github.com/tmsmith/Dapper-Extensions/wiki/Predicates
/// https://github.com/zzzprojects/Dapper-Plus
///

public class DbClient : IDisposable, IDbClient
{
string connStr = @"Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True;uid=sa;pwd=123456";
int commandTimeout = 30;
///
/// 数据客户端
///

/// 数据库连接字符串
/// 数据库类型
/// 操作超时,单位:秒
/// 是否自动更实体对象的创建时间、更新时间
public DbClient(string connStr, int commandTimeout = 30)
{
if (string.IsNullOrWhiteSpace(connStr)) throw new NoNullAllowedException("数据库连接字符串不允许为空");
this.connStr = connStr;
this.commandTimeout = commandTimeout;
DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect();
Mappings.Initialize();
//DapperExtensions.DapperExtensions.DefaultMapper = typeof(CustomPluralizedMapper<>);
}
///
/// 获取打开的连接
///

/// MSSql数据库下有效:如果为 true,则应用程序可以保留多活动结果集 (MARS)。 如果为 false,则应用程序必须处理或取消一个批处理中的所有结果集,然后才能对该连接执行任何其他批处理。
///
public IDbConnection GetOpenConnection()
{
IDbConnection connection = null;
string cs = connStr;
connection = new MySqlConnection(cs);
connection.Open();
return connection;
}

#region Add

///


/// 批量新增
///

/// 实体类型
/// 实体对象集
public void Add(IEnumerable entities) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
using (var trans = cnn.BeginTransaction())
{
try
{
cnn.Insert(entities, trans, commandTimeout);
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
}

//using (IDbConnection cnn = GetOpenConnection())
//{
// var trans = cnn.BeginTransaction();
// cnn.Execute(@"insert Member(Username, IsActive) values(@Username, @IsActive)", entities, transaction: trans);
// trans.Commit();
//}
}

///


/// 新增
///

/// 实体类型
/// 实体对象
/// 实体对象
public T Add(T entity) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
T res = null;
using (var trans = cnn.BeginTransaction())
{
try
{
int id = cnn.Insert(entity, trans, commandTimeout);
if (id > 0)
{
res = entity;
}
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
return res;
}
}

#endregion

#region Update

///


/// 更新
///

/// 实体类型
/// 实体对象
/// 是否成功
public bool Update(T entity) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
bool res = false;
using (var trans = cnn.BeginTransaction())
{
try
{
res = cnn.Update(entity, trans, commandTimeout);
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
return res;
}
}

public bool Update(IEnumerable entities) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
bool res = false;
using (var trans = cnn.BeginTransaction())
{
try
{
trans.BulkUpdate(entities);
res = true;
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
return res;
}
}

#endregion

#region Delete

///


/// 删除
///

/// 实体类型
/// 实体对象
/// 是否成功
public bool Delete(T entity) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
bool res = false;
using (var trans = cnn.BeginTransaction())
{
try
{
res = cnn.Delete(entity, trans, commandTimeout);
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
return res;
}
}

///


/// 条件删除
///

/// 实体类型
/// 实体对象
/// 是否成功
public bool Delete(object predicate) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
bool res = false;
using (var trans = cnn.BeginTransaction())
{
try
{
res = cnn.Delete(predicate, trans, commandTimeout);
}
catch (DataException ex)
{
trans.Rollback();
throw ex;
}
trans.Commit();
}
return res;
}
}

#endregion

#region Query/Get

///


/// 查询单个结果
///

/// 实体类型
/// 实体的Id属性值
/// 查询结果
public T Get(object id) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
T res = null;
try
{
res = cnn.Get(id, null, commandTimeout);
}
catch (DataException ex)
{
throw ex;
}
return res;
}
}

///


/// 查询结果集合
///

/// 实体类型
/// 分页查询条件
/// 是否排序
/// 查询结果
public IEnumerable Get(object predicate = null, IList sort = null) where T : class, new()
{
using (IDbConnection cnn = GetOpenConnection())
{
IEnumerable res = null;
try
{
res = cnn.GetList(predicate, sort, null, commandTimeout);
}
catch (DataException ex)
{
throw ex;
}
return res;
}
}

///


/// 查询结果分页
///

/// 实体类型
/// 分页查询条件
/// 是否排序
/// 分页索引
/// 分页大小
/// 查询结果
public PageInfo Get(object predicate, IList sort, int pageIndex, int pageSize) where T : class, new()
{
if (sort == null) throw new ArgumentNullException("sort 不允许为null");
if (pageIndex < 0) pageIndex = 0;
using (IDbConnection cnn = GetOpenConnection())
{
PageInfo pInfo = null;
try
{
int count = cnn.Count(predicate, null, commandTimeout);
pInfo = new PageInfo();
pInfo.TotalCount = count;
pInfo.Data = cnn.GetPage(predicate, sort, pageIndex, pageSize, null, commandTimeout);
}
catch (DataException ex)
{
throw ex;
}
return pInfo;
}
}

#endregion

#region IDisposable Support

private bool disposedValue = false; // 要检测冗余调用

protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: 释放托管状态(托管对象)。
}

// TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
// TODO: 将大型字段设置为 null。

disposedValue = true;
}
}

// TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
// ~DbClient() {
// // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
// Dispose(false);
// }

// 添加此代码以正确实现可处置模式。
void IDisposable.Dispose()
{
// 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
Dispose(true);
// TODO: 如果在以上内容中替代了终结器,则取消注释以下行。
// GC.SuppressFinalize(this);
}

#endregion
}
}

public class FlowCell
{
public int Id { get; set; }
public int type_id { get; set; }
public string comId { get; set; }
public string bloc_name { get; set; }
public string cell_number { get; set; }
public string name { get; set; }

public int flows { get; set; }

public int status { get; set; }

public int del { get; set; }
}

使用:

public void Statistics()
{
try
{
DbClient dbClient = new DbClient(mysqlConstr);
var pg = new PredicateGroup { Operator = GroupOperator.Or, Predicates = new List() };
pg.Predicates.Add(Predicates.Field(f => f.status, Operator.Eq, 1));
pg.Predicates.Add(Predicates.Field(f => f.del, Operator.Eq, 0));

var flowCell = dbClient.Get(4);

IList sorts = new List();
ISort sort = new Sort();
sort.Ascending = false;
sort.PropertyName = "name"; //如果有Map,则此次要填写Map对象的字段名称,而不是数据库表字段名称
sorts.Add(sort);
var flowCell2 = dbClient.Get(pg, sorts);

var flowCell3 = dbClient.Get(pg, sorts, 0, 2);
}
catch (Exception ex)
{

}
}




本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/6424774.html,如需转载请自行联系原作者

你可能感兴趣的:(C# Dapper 简单实例)