? C#亚博足球娱乐场注册--任意三数字加yabo.com直达官网之[开源]Dapper Repository 一种实现方式 亚博足球娱乐场注册,亚博娱乐全天彩,亚博官网赢钱不给
VB.net 2010 视频亚博足球娱乐场注册--任意三数字加yabo.com直达官网 VB.net 2010 视频亚博足球娱乐场注册--任意三数字加yabo.com直达官网 VB.net 2010 视频亚博足球娱乐场注册--任意三数字加yabo.com直达官网
SQL Server 2008 视频亚博足球娱乐场注册--任意三数字加yabo.com直达官网 c#入门经典亚博足球娱乐场注册--任意三数字加yabo.com直达官网 Visual Basic从门到精通视频亚博足球娱乐场注册--任意三数字加yabo.com直达官网
  • C#亚博足球娱乐场注册--任意三数字加yabo.com直达官网之[开源]Dapper Repository 一种实现方式

  • 2019-04-13 21:49 来源:未知
  1. 接着上篇[开源]Entity Framework 6 Repository 一种实现方式
  2. 由于Dapper 本身就是轻量级Orm特性,这里参考Creating a Data Repository using Dapper?dynamic queries in dapper?代码,来解决实体类与Expression<>> predicate问题;
  3. 您可以通过Nuget:Install-Package MasterChief.DotNet.Core.Dapper;
  4. 您可以通过GitHub:MasterChief?查看具体源码以及单元测试;
  5. 欢迎Star,欢迎Issues;

插播一条求职#

  1. 小弟拥有多年C#开发经验,从事过路灯,消防平台物联网平台开发,坐标上海;
  1. 如果贵司在招聘,烦请大佬考虑下,联系邮箱:MeetYan@outlook.com

基于Dapper 的Repository实现#


	
Copy
public abstract class DapperDbContextBase : IDbContext { #region Constructors /// /// 构造函数 /// /// 连接字符串 protected DapperDbContextBase(string connectString) { ConnectString = connectString; } #endregion Constructors #region Properties /// /// 获取 是否开启事务提交 /// public IDbTransaction CurrentTransaction { get; private set; } #endregion Properties #region Fields /// /// 当前数据库连接 /// public IDbConnection CurrentConnection => TransactionEnabled ? CurrentTransaction.Connection : CreateConnection(); /// /// 获取 是否开启事务提交 /// public bool TransactionEnabled => CurrentTransaction != null; /// /// 连接字符串 /// protected readonly string ConnectString; #endregion Fields #region Methods /// /// 显式开启数据上下文事务 /// /// 指定连接的事务锁定行为 public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified) { if (!TransactionEnabled) CurrentTransaction = CreateConnection().BeginTransaction(isolationLevel); } /// /// 提交当前上下文的事务更改 /// /// 提交数据更新时发生异常:" + msg public void Commit() { if (TransactionEnabled) try { CurrentTransaction.Commit(); } catch (Exception ex) { if (ex.InnerException?.InnerException is SqlException sqlEx) { var msg = DataBaseHelper.GetSqlExceptionMessage(sqlEx.Number); throw new DataAccessException("提交数据更新时发生异常:" + msg, sqlEx); } throw; } } /// /// 创建记录 /// /// 需要操作的实体类 /// 操作是否成功 public bool Create(T entity) where T : ModelBase { ValidateOperator.Begin().NotNull(entity, "需要新增的数据记录"); // insert single data always return 0 but the data is inserted in database successfully //https://github.com/StackExchange/Dapper/issues/587 //List data = new List() { entity }; return CurrentConnection.Insert(new List {entity}, CurrentTransaction) > 0; #region 测试代码 //string sql = @"INSERT INTO [dbo].[EFSample] // ([ID] // ,[CreateTime] // ,[ModifyTime] // ,[Available] // ,[UserName]) //VALUES // (@ID // ,@CreateTime // ,@ModifyTime // ,@Available // ,@UserName)"; //return CurrentConnection.Execute(sql, entity) > 0; #endregion 测试代码 } /// /// 创建数据库连接IDbConnection /// /// public abstract IDbConnection CreateConnection(); /// /// 删除记录 /// /// 操作是否成功 /// 需要操作的实体类. public bool Delete(T entity) where T : ModelBase { ValidateOperator.Begin().NotNull(entity, "需要删除的数据记录"); return CurrentConnection.Delete(entity); } /// /// 执行与释放或重置非托管资源关联的应用程序定义的任务。 /// public void Dispose() { if (CurrentTransaction != null) { CurrentTransaction.Dispose(); CurrentTransaction = null; } CurrentConnection?.Dispose(); } /// /// 条件判断是否存在 /// /// 是否存在 /// 判断条件委托 public bool Exist(Expression<>bool>> predicate = null) where T : ModelBase { var tableName = GetTableName(); var queryResult = DynamicQuery.GetDynamicQuery(tableName, predicate); var result = CurrentConnection.ExecuteScalar(queryResult.Sql, (object) queryResult.Param, CurrentTransaction); return result != null; } /// /// 根据id获取记录 /// /// 记录 /// id. public T GetByKeyId(object id) where T : ModelBase { ValidateOperator.Begin().NotNull(id, "Id"); return CurrentConnection.Get(id, CurrentTransaction); } /// /// 条件获取记录集合 /// /// 集合 /// 筛选条件. public List GetList(Expression<>bool>> predicate = null) where T : ModelBase { var tableName = GetTableName(); var queryResult = DynamicQuery.GetDynamicQuery(tableName, predicate); return CurrentConnection.Query(queryResult.Sql, (object) queryResult.Param, CurrentTransaction).ToList(); } /// /// 条件获取记录第一条或者默认 /// /// 记录 /// 筛选条件. public T GetFirstOrDefault(Expression<>bool>> predicate = null) where T : ModelBase { var tableName = GetTableName(); var queryResult = DynamicQuery.GetDynamicQuery(tableName, predicate); return CurrentConnection.QueryFirst(queryResult.Sql, (object) queryResult.Param, CurrentTransaction); } /// /// 条件查询 /// /// IQueryable /// 筛选条件. public IQueryable Query(Expression<>bool>> predicate = null) where T : ModelBase { throw new NotImplementedException(); } /// /// 显式回滚事务,仅在显式开启事务后有用 /// public void Rollback() { if (TransactionEnabled) CurrentTransaction.Rollback(); } /// /// 执行Sql 脚本查询 /// /// Sql语句 /// 参数 /// 集合 public IEnumerable SqlQuery(string sql, IDbDataParameter[] parameters) { ValidateOperator.Begin() .NotNullOrEmpty(sql, "Sql语句"); var dataParameters = CreateParameter(parameters); return CurrentConnection.Query(sql, dataParameters, CurrentTransaction); } /// /// 根据记录 /// /// 操作是否成功. /// 实体类记录. public bool Update(T entity) where T : ModelBase { ValidateOperator.Begin().NotNull(entity, "需要更新的数据记录"); return CurrentConnection.Update(entity, CurrentTransaction); } private DapperParameter CreateParameter(IDbDataParameter[] parameters) { if (!(parameters?.Any() ?? false)) return null; var dataParameters = new DapperParameter(); foreach (var parameter in parameters) dataParameters.Add(parameter); return dataParameters; } private string GetTableName() where T : ModelBase { var tableCfgInfo = AttributeHelper.Get(); return tableCfgInfo != null ? tableCfgInfo.Name.Trim() : typeof(T).Name; } #endregion Methods }

使用方法#


	
Copy
public class SampleService : ISampleService { private readonly IDatabaseContextFactory _contextFactory; public SampleService(IDatabaseContextFactory contextFactory) { _contextFactory = contextFactory; } /// /// 创建 /// /// EFSample /// public bool Create(EfSample sample) { using (IDbContext context = _contextFactory.Create()) { return context.Create(sample); } } /// /// 条件查询 /// /// The predicate. /// /// public EfSample GetFirstOrDefault(Expression<>bool>> predicate = null) { using (IDbContext context = _contextFactory.Create()) { return context.GetFirstOrDefault(predicate); } } /// /// 根据主键查询 /// /// The identifier. /// /// public EfSample GetByKeyId(Guid id) { using (IDbContext context = _contextFactory.Create()) { return context.GetByKeyId(id); } } /// /// 条件查询集合 /// /// The predicate. /// public List GetList(Expression<>bool>> predicate = null) { using (IDbContext context = _contextFactory.Create()) { return context.GetList(predicate); } } /// /// 添加判断是否存在 /// /// The predicate. /// public bool Exist(Expression<>bool>> predicate = null) { using (IDbContext context = _contextFactory.Create()) { return context.Exist(predicate); } } /// /// 脚本查询 /// /// The SQL. /// DbParameter[] /// public List SqlQuery(string sql, DbParameter[] parameter) { using (IDbContext context = _contextFactory.Create()) { return context.SqlQuery(sql, parameter)?.ToList(); } } /// /// 更新 /// /// The sample. /// public bool Update(EfSample sample) { using (IDbContext context = _contextFactory.Create()) { return context.Update(sample); } } /// /// 事务 /// /// The sample. /// The sample2. /// public bool CreateWithTransaction(EfSample sample, EfSample sample2) { bool result; using (IDbContext context = _contextFactory.Create()) { try { context.BeginTransaction();//开启事务 context.Create(sample); context.Create(sample2); context.Commit(); result = true; } catch (Exception) { context.Rollback(); result = false; } } return result; } /// /// 删除 /// /// /// public bool Delete(EfSample sample) { using (IDbContext context = _contextFactory.Create()) { return context.Delete(sample); } } }

结语#

  1. Dapper与Entity Framework都是通过IRepository实现,所以您可以通过Ioc切换;
  2. 该篇的单元测试写法与上篇一致;
  3. 小弟不才,大佬轻拍;

作者:YanZhiwei

出处:https://www.cnblogs.com/MeetYan/p/10681353.html

本站使用「署名 4.0 国际」创作共享协议,转载请在文章明显位置注明作者及出处。


相关亚博足球娱乐场注册--任意三数字加yabo.com直达官网