Create DbContexts that handle DatabaseFactory to make it easier to use DapperExtensions

I am currently trying to create an abstract base repository using some of the core CRUD functions proposed by DapperExtensions . But the example code uses the SqlConnection, which is created to connect to the SQL Server database. I want to be able to connect to all types of database (SQL Server, MySql, etc.). Also, their sample code is repeated for each CRUD function, as shown in the code below.

using (SqlConnection cn = new SqlConnection(_connectionString))
{
    cn.Open();
    //Code doing something here...
    cn.Close();
}

So, I was thinking of creating a DbContext that can handle the creation, opening and closing of a connection, and can also create the correct connection object depending on the type of database I want to use (a kind of factory database ).

Is there anyone who has already done this and could share their code?

Thanks guys!

+1
source share
2 answers

You are using Dapper-Extensions; The following code is only with Dapper. But this does not change the whole concept. Instead sqlyou need to go through poco.

, IUnitOfWork DalSession. BaseDal 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;
    }
}

1 , Dapper-Extensions, , .

0
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

Source: https://habr.com/ru/post/1672870/


All Articles