创建一个处理DatabaseFactory的DbContext以更轻松地使用DapperExtensions [英] Create a DbContext that handle a DatabaseFactory to use DapperExtensions more easily
问题描述
这几天,我尝试使用 DapperExtensions 。但是作为示例给出的代码使用了SqlConnection,该连接用于连接到SQL Server数据库。我希望能够连接到所有类型的数据库(SQL Server,MySql等)。同样,每个CRUD函数的代码示例也如下所示:
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 made to connect to a SQL Server database. I want to be able to connect to all kind of Database (SQL Server, MySql, etc...). Also their code sample is repeated for each CRUD function as the code below show
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
//Code doing something here...
cn.Close();
}
所以我在考虑创建 DbContext 可以处理连接的创建,打开和关闭,还可以根据我要使用的数据库类型(一种数据库工厂)来创建正确的连接对象。
So i was thinking about to create a DbContext that can handle the creation, the opening and closing of the connection and also can create the right connection object depending on the database type I want to use (a kind of database factory).
有没有人做过并且可以共享他的代码?
Is there somebody that already done it and could share his code?
谢谢大家!
推荐答案
您正在使用Dapper-Extensions;以下代码仅适用于Dapper。但这并不会改变整个概念。只需使用 poco
代替 sql
。
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
.
请参考此答案,以了解我如何实现 IUnitOfWork
和 DalSession
。在下面的代码中, BaseDal
就像 BaseRepository
。
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;
}
}
编辑1
例如,带有Dapper-Extensions的代码,请参阅我最近发布的此答案。
这篇关于创建一个处理DatabaseFactory的DbContext以更轻松地使用DapperExtensions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!