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

亡梦爱人 提交于 2019-12-02 06:23:58

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.

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;
    }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!