一个基于Dapper的DbContext封装

开篇:  

各位博客园的园友好,这是我第一次在园子里写些东西。我是一个技术菜鸟,伴随着苦与乐,已经渡过了8年的IT技术生涯,准备利用这片天地向大家交流学习。

正题:

今天上午闲来无事,利用上午时间写了一个基于Dapper的DbContext封装。还有很多地方没有完善,敬请期待下次更新。

 1、RepositoryContext存储上下文

     接口:

  
1  public interface IRepositoryContext : IDisposable
2     {
3         IDbConnection Conn { get; }
4         void InitConnection();
5     }
View Code

  实现:    

  
    public class RepositoryContext : DisposableObject, IUnitOfWork, IRepositoryContext
    {
        private readonly ConnectionStringSettings _connectionSeting =
            ConfigurationManager.ConnectionStrings["BudisengFirstDemoInfo"];

        public RepositoryContext()
        {
            InitConnection();
        }

        public RepositoryContext(ConnectionStringSettings connectionSeting)
        {
            // TODO: Complete member initialization
            this._connectionSeting = connectionSeting;
            InitConnection();
        }

        public IDbConnection Conn { private set; get; }

        public void InitConnection()
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(this._connectionSeting.ProviderName);
            this.Conn = dbfactory.CreateConnection();
            if (Conn != null) this.Conn.ConnectionString = this._connectionSeting.ConnectionString;
        }

        private bool _committed = true;
        private readonly object _sync = new object();

        public bool Committed
        {
            set { _committed = value; }
            get { return _committed; }
        }
        public IDbTransaction Tran { private set; get; }
        public void BeginTran()
        {
            this.Tran = this.Conn.BeginTransaction();
            this.Committed = false;
        }

        public void Commit()
        {
            if (Committed) return;
            lock (_sync)
            {
                this.Tran.Rollback();
                this._committed = true;
            }
        }

        public void Rollback()
        {
            if (Committed) return;
            lock (_sync)
            {
                this.Tran.Rollback();
                this._committed = true;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            if (this.Conn.State != ConnectionState.Open) return;
            Commit();
            this.Conn.Close();
            this.Conn.Dispose();
        }
    }
View Code

 2、存储库

     接口:

  
 1     public interface IRepository<T>
 2         where T : class
 3     {
 4         T Add(T model);
 5         List<T> Add(IList<T> modeList ); 
 6         void Update(T model);
 7         void Update(IList<T> modeList);
 8         T Find(int id);
 9         void Remove(int id);
10         void Remove(T model);
11         T QueryFirst(object sqlParas);
12         T QueryFirst(string sql, object sqlParas);
13         IList<T> Query(object sqlParas);
14         IList<T> Query(string sql, object sqlParas);
15         IList<T> Query(object sqlParas,int pageSize,int pageIndex);
16         
17     }
View Code

  实现:

  
 1 public class Repository<T> : IRepository<T> where T : class, IEntity
 2        {
 3        protected IRepositoryContext Context;
 4        protected IDbConnection Conn;
 5 
 6        public Repository(IRepositoryContext context)
 7        {
 8            Context = context;
 9            Conn = Context.Conn;
10        }
11 
12         public T Add(T model)
13         {
14            return this.Conn.Insert(model);
15         }
16 
17         public void Update(T model)
18         {
19             this.Conn.Update(model);
20         }
21 
22         public T QueryFirst(object sqlParas)
23         {
24             return Conn.Select<T>(sqlParas).FirstOrDefault();
25         }
26 
27 
28 
29 
30 
31         public System.Collections.Generic.List<T> Add(System.Collections.Generic.IList<T> modeList)
32         {
33             throw new System.NotImplementedException();
34         }
35 
36         public void Update(System.Collections.Generic.IList<T> modeList)
37         {
38             throw new System.NotImplementedException();
39         }
40 
41         public T Find(int id)
42         {
43             throw new System.NotImplementedException();
44         }
45 
46         public void Remove(int id)
47         {
48             throw new System.NotImplementedException();
49         }
50 
51         public void Remove(T model)
52         {
53             throw new System.NotImplementedException();
54         }
55 
56         public T QueryFirst(string sql, object sqlParas)
57         {
58             throw new System.NotImplementedException();
59         }
60 
61         public System.Collections.Generic.IList<T> Query(object sqlParas)
62         {
63             throw new System.NotImplementedException();
64         }
65 
66         public System.Collections.Generic.IList<T> Query(string sql, object sqlParas)
67         {
68             throw new System.NotImplementedException();
69         }
70 
71         public System.Collections.Generic.IList<T> Query(object sqlParas, int pageSize, int pageIndex)
72         {
73             throw new System.NotImplementedException();
74         }
75        }
View Code

3、基础架构

  IUnitOfWork   

  
1     public interface IUnitOfWork
2     {
3         bool Committed { set; get; }
4         IDbTransaction Tran { get; }
5         void BeginTran();
6         void Commit();
7         void Rollback();
8     }
View Code

  DisposableObject

  
 1     public abstract class DisposableObject : IDisposable
 2     {
 3         ~DisposableObject()
 4         {
 5             this.Dispose(false);
 6         }
 7 
 8         protected void ExplicitDispose()
 9         {
10             this.Dispose(true);
11             GC.SuppressFinalize(this);
12         }
13 
14         public void Dispose()
15         {
16             this.ExplicitDispose();
17         }
18     }
View Code

4、Dapper扩展

  
 1   public static class DapperExtensions
 2     {
 3         public static T Insert<T>(this IDbConnection con, T item, IDbTransaction transaction = null) where T : IEntity
 4         {
 5             return con.Query<T>(DynamicQuery.GetInsertQuery(typeof(T).Name, item), item, transaction).First();
 6         }
 7 
 8         public static void Update<T>(this IDbConnection con,  T item, IDbTransaction transaction = null) where T : IEntity
 9         {
10             con.Execute(DynamicQuery.GetUpdateQuery(typeof(T).Name, item), item, transaction);
11         }
12         public static IEnumerable<T> Select<T>(this IDbConnection con,object criteria = null)
13         {
14             var properties =PropertyManage.ParseProperties(criteria);
15             var sqlPairs = PropertyManage.GetSqlPairs(properties.AllNames, " AND ");
16             var sql = string.Format("SELECT * FROM [{0}] WHERE {1}", typeof(T).Name, sqlPairs);
17             return con.Query<T>(sql, properties.AllPairs);
18         }
19 
20     }
View Code

  详见附件:

      DbContext for Dapper

原文地址:https://www.cnblogs.com/tuousi99/p/4455573.html