三、BaseRepository是个抽象类,有些比较复杂的sql语句通过EF来处理比较麻烦,还需要直接操作sql语句的方法,因不同的数据库sql语句不一样,针对不同的数据,继承BaseRepository这个基类,重写sql语句方法,下面简单实现SqlServerRepository仓储
public class SqlServerRepository<TEntity,TKey>: BaseRepository<TEntity,TKey>,IRepository<TEntity,TKey> where TEntity : class
{
protected ConfigOption _dbOpion;
public SqlServerRepository(GeneralDbContext generalDbContext,IOptionsSnapshot<ConfigOption> options)
:base(generalDbContext)
{
_dbOpion = options.Get("config");
_connectionString = _dbOpion.ReadWriteHosts;
}
#region 插入数据
/// <summary>
/// 使用Bulk批量插入数据(适合大数据量,速度非常快)
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entities">数据</param>
public override void BulkInsert<T>(List<T> entities)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString =_connectionString ;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
string tableName = string.Empty;
var tableAttribute = typeof(T).GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();
if (tableAttribute != null)
tableName = ((TableAttribute)tableAttribute).Name;
else
tableName = typeof(T).Name;
SqlBulkCopy sqlBC = new SqlBulkCopy(conn)
{
BatchSize = 100000,
BulkCopyTimeout = 0,
DestinationTableName = tableName
};
using (sqlBC)
{
sqlBC.WriteToServer(entities.ToDataTable());
}
}
}
public override DataTable GetDataTableWithSql(string sql)
{
return GetDataTableWithSql(sql);
}
public override DataTable GetDataTableWithSql(string sql, List<DbParameter> spList=null)
{
DataTable dt = new DataTable(); ;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.SelectCommand.CommandType = CommandType.Text;
if (spList.ToArray() != null)
{
da.SelectCommand.Parameters.AddRange(spList.ToArray());
}
da.Fill(dt);
}
return dt;
}
#endregion
}