Create a DbContext that handle a DatabaseFactory to use DapperExtensions more easily

后端 未结 2 1744
走了就别回头了
走了就别回头了 2021-01-24 13:37

This days I try to create an abstract base repository using some basic CRUD functions proposed by DapperExtensions. But the code given as an exemple use a SqlConnection which is

相关标签:
2条回答
  • 2021-01-24 14:16
    public abstract class ABaseRepository<M> : IBaseRepository<M>
            where M : BaseModel
        {
            private static DbProviderFactory factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ProviderName);
            protected static DbConnection connection;
    
        public static IDbConnection CreateOpenConnection()
        {
            connection = factory.CreateConnection();
            connection.Open();
    
            return connection;
        }
    
        public dynamic Insert(M model)
        {
            dynamic multiKey;
            using (IDbConnection con = CreateOpenConnection())
            {
                multiKey = con.Insert(model);
            }
    
            return multiKey;
        }
     }
    
    0 讨论(0)
  • 2021-01-24 14:27

    You are using Dapper-Extensions; following code is with Dapper only. But it does not change the entire concept. Just instead of sql you need to pass poco.

    Refer this answer for how I implemented IUnitOfWork and DalSession. In below code, BaseDal is just like BaseRepository.

    public abstract class BaseDal
    {
        internal BaseDal(IUnitOfWork unitOfWork)
        {
            dapperHandler = new DapperHandler(unitOfWork);
        }
    
        DapperHandler dapperHandler = null;
    
        protected T Get<T>(string sql, DynamicParameters param) where T : class
        {
            var result = dapperHandler.Query<T>(sql, param).FirstOrDefault();
            return result;
        }
    
        protected List<T> GetList<T>(string sql, DynamicParameters param) where T : class
        {
            var result = dapperHandler.Query<T>(sql, param).ToList();
            return result;
        }
    
        protected int Insert(string sql, DynamicParameters param)
        {
            var result = dapperHandler.Execute(sql, param);
            return result;
        }
    }
    

    Edit 1 For example code with Dapper-Extensions, refer this answer that I recently posted.

    0 讨论(0)
提交回复
热议问题