ABP框架 sql语句(转载)

时间:2024-11-21 17:34:31

ABP.Core实现SQL语句仓储,支持EF.Core兼容的数据库

 来源:https://blog.****.net/qq_28699537/article/details/80522680?tdsourcetag=s_pcqq_aiomsg
2018年05月31日 13:22:22 余业勤 阅读数:82

ISqlRepository.cs代码

public interface ISqlRepository : IRepository
{
/// <summary>
/// 执行给定的命令
/// </summary>
/// <param name="sql">命令字符串</param>
/// <param name="parameters">要应用于命令字符串的参数</param>
/// <returns>执行命令后由数据库返回的结果</returns>
Task<int> Execute(string sql, params object[] parameters); /// <summary>
/// 执行语句返回dataset,注意参数用@p0、@p1、@p3...以此类推,要按照顺序
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="parameters">sql参数</param>
/// <returns>dataset</returns>
Task<DataTable> ExecuteDataTable(string sql, params object[] parameters);
}

SqlRepository.cs代码

public class SqlRepository : ISqlRepository, ITransientDependency
{
private readonly IDbContextProvider<SmartDbContext> _dbContextProvider;
public SqlRepository(IDbContextProvider<SmartDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
} /// <summary>
/// 执行给定的命令
/// </summary>
/// <param name="sql">命令字符串</param>
/// <param name="parameters">要应用于命令字符串的参数</param>
/// <returns>执行命令后由数据库返回的结果</returns>
public async Task<int> Execute(string sql, params object[] parameters)
{
return await _dbContextProvider.GetDbContext().Database.ExecuteSqlCommandAsync(sql, parameters);
} public async Task<DataTable> ExecuteDataTable(string sql, params object[] parameters)
{
return await Task.Run(() =>
{ var db = _dbContextProvider.GetDbContext().Database;
var conn = db.GetDbConnection();
if (conn.State != ConnectionState.Open)
conn.Open(); DataTable dt = new DataTable(); RawSqlCommand rawSqlCommand = db.GetService<IRawSqlCommandBuilder>().Build(sql, parameters); RelationalDataReader query = rawSqlCommand.RelationalCommand.ExecuteReader(db.GetService<IRelationalConnection>(), parameterValues: rawSqlCommand.ParameterValues); DbDataReader dr = query.DbDataReader; int fieldCount = dr.FieldCount; //获取schema并填充第一行数据
if (dr.Read())
{
for (int i = ; i < fieldCount; i++)
{
string colName = dr.GetName(i);
dt.Columns.Add(colName, dr.GetFieldType(i));
}
DataRow newrow = dt.NewRow();
for (int i = ; i < fieldCount; i++)
{
newrow[i] = dr[i];
}
dt.Rows.Add(newrow);
}
//填充后续数据
while (dr.Read())
{
DataRow newrow = dt.NewRow();
for (int i = ; i < fieldCount; i++)
{
newrow[i] = dr[i];
}
dt.Rows.Add(newrow);
}
dt.AcceptChanges(); return
 思路:
1 ef可以直接写sql,然后试着调用这个方法。
2 ORM从EF切换到ADO或NHibernate,然后试着调用这个方法。
3 若ORM无法切换到原生ADO,基础设施层加一个原生ADO层,然后(应用服务层)试着调用这个方法。