本篇是对efcore 进行下封装并实现基本的增删改查的同步异步方法及针对不同数据库的批量插入、sql语句直接操作数据库;

       一、 先定义基础仓储接口irepository

   

  public  interface irepository<tentity,tkey> where tentity : class
    {
        #region 查找数据
        long count(expression<func<tentity, bool>> predicate = null);
        task<long> countasync(expression<func<tentity, bool>> predicate = null);

        tentity get(expression<func<tentity, bool>> predicate, bool isnotracking);
        task<tentity> getasync(expression<func<tentity, bool>> predicate, bool isnotracking);

     
        task<tentity> getasync(tkey id);

        iqueryable<tentity> load(expression<func<tentity, bool>> predicate , bool isnotracking);
        task<iqueryable<tentity>> loadasync(expression<func<tentity, bool>> predicate , bool isnotracking);

        list<tentity> getlist(expression<func<tentity, bool>> predicate, string ordering, bool isnotracking );
        task<list<tentity>> getlistasync(expression<func<tentity, bool>> predicate, string ordering, bool isnotracking );
       
        #endregion

        #region 插入数据
        bool insert(tentity entity, bool issavechange);
        task<bool> insertasync(tentity entity, bool issavechange);
        bool insert(list<tentity> entitys, bool issavechange = true);
        task<bool> insertasync(list<tentity> entitys, bool issavechange);
        #endregion

        #region 删除(删除之前需要查询)
        bool delete(tentity entity, bool issavechange);
        bool delete(list<tentity> entitys, bool issavechange);
        task<bool> deleteasync(tentity entity, bool issavechange);
        task<bool> deleteasync(list<tentity> entitys, bool issavechange = true);
        #endregion

        #region 修改数据
       bool update(tentity entity, bool issavechange, list<string> updatepropertylist);
       task<bool> updateasync(tentity entity, bool issavechange, list<string> updatepropertylist);
       bool update(list<tentity> entitys, bool issavechange);
       task<bool> updateasync(list<tentity> entitys, bool issavechange );
        #endregion

        #region 执行sql语句
        void bulkinsert<t>(list<t> entities);
        int executesql(string sql);
        task<int> executesqlasync(string sql);
        int executesql(string sql, list<dbparameter> splist);
        task<int> executesqlasync(string sql, list<dbparameter> splist);
        datatable getdatatablewithsql(string sql);

        datatable getdatatablewithsql(string sql, list<dbparameter> splist);

      

        #endregion

二、实现irepository接口

   public abstract  class baserepository<tentity,tkey> :irepository<tentity,tkey> where tentity : class
{
private readonly dbset<tentity> _dbset;
public generaldbcontext _dbcontext { get; } = null;
/// <summary>
/// 连接字符串
/// </summary>
protected string _connectionstring { get; set; }
/// <summary>
/// 数据库类型
/// </summary>
private databasetype _dbtype { get; set; }
public baserepository(generaldbcontext context)
{
_dbcontext = context;
_dbset = _dbcontext.set<tentity>();
}
public databasefacade database => _dbcontext.database;
public iqueryable<tentity> entities => _dbset.asqueryable().asnotracking();
public int savechanges()
{
return _dbcontext.savechanges();
}
public async task<int> savechangesasync()
{
return await _dbcontext.savechangesasync();
}
public bool any(expression<func<tentity, bool>> wherelambd)
{
return _dbset.where(wherelambd).any();
}
#region 插入数据
public bool insert(tentity entity, bool issavechange = true)
{
_dbset.add(entity);
if (issavechange)
{
return savechanges() > 0;
}
return false;
}
public async task<bool> insertasync(tentity entity, bool issavechange = true)
{
_dbset.add(entity);
if (issavechange)
{
return await savechangesasync() > 0;
}
return false;
}
public bool insert(list<tentity> entitys, bool issavechange = true)
{
_dbset.addrange(entitys);
if (issavechange)
{
return savechanges() > 0;
}
return false;
}
public async task<bool> insertasync(list<tentity> entitys, bool issavechange = true)
{
_dbset.addrange(entitys);
if (issavechange)
{
return await savechangesasync() > 0;
}
return false;
}
#endregion
#region 删除
public bool delete(tentity entity, bool issavechange = true)
{
_dbset.attach(entity);
_dbset.remove(entity);
return issavechange ? savechanges() > 0 : false;
}
public bool delete(list<tentity> entitys, bool issavechange = true)
{
entitys.foreach(entity =>
{
_dbset.attach(entity);
_dbset.remove(entity);
});
return issavechange ? savechanges() > 0 : false;
}
public virtual async task<bool> deleteasync(tentity entity, bool issavechange = true)
{
_dbset.attach(entity);
_dbset.remove(entity);
return issavechange ? await savechangesasync() > 0 : false;
}
public virtual async task<bool> deleteasync(list<tentity> entitys, bool issavechange = true)
{
entitys.foreach(entity =>
{
_dbset.attach(entity);
_dbset.remove(entity);
});
return issavechange ? await savechangesasync() > 0 : false;
}
#endregion
#region 更新数据
public bool update(tentity entity, bool issavechange = true, list<string> updatepropertylist = null)
{
if (entity == null)
{
return false;
}
_dbset.attach(entity);
var entry = _dbcontext.entry(entity);
if (updatepropertylist == null)
{
entry.state = entitystate.modified;//全字段更新
}
else
{
updatepropertylist.foreach(c => {
entry.property(c).ismodified = true; //部分字段更新的写法
});
}
if (issavechange)
{
return savechanges() > 0;
}
return false;
}
public bool update(list<tentity> entitys, bool issavechange = true)
{
if (entitys == null || entitys.count == 0)
{
return false;
}
entitys.foreach(c => {
update(c, false);
});
if (issavechange)
{
return savechanges() > 0;
}
return false;
}
public async task<bool> updateasync(tentity entity, bool issavechange = true, list<string> updatepropertylist = null)
{
if (entity == null)
{
return false;
}
_dbset.attach(entity);
var entry = _dbcontext.entry<tentity>(entity);
if (updatepropertylist == null)
{
entry.state = entitystate.modified;//全字段更新
}
else
{
updatepropertylist.foreach(c => {
entry.property(c).ismodified = true; //部分字段更新的写法
});
}
if (issavechange)
{
return await savechangesasync() > 0;
}
return false;
}
public async task<bool> updateasync(list<tentity> entitys, bool issavechange = true)
{
if (entitys == null || entitys.count == 0)
{
return false;
}
entitys.foreach(c => {
_dbset.attach(c);
_dbcontext.entry<tentity>(c).state = entitystate.modified;
});
if (issavechange)
{
return await savechangesasync() > 0;
}
return false;
}
#endregion
#region 查找
public long count(expression<func<tentity, bool>> predicate = null)
{
if (predicate == null)
{
predicate = c => true;
}
return _dbset.longcount(predicate);
}
public async task<long> countasync(expression<func<tentity, bool>> predicate = null)
{
if (predicate == null)
{
predicate = c => true;
}
return await _dbset.longcountasync(predicate);
}
public tentity get(tkey id)
{
if (id == null)
{
return default(tentity);
}
return _dbset.find(id);
}
public tentity get(expression<func<tentity, bool>> predicate = null, bool isnotracking = true)
{
var data = isnotracking ? _dbset.where(predicate).asnotracking() : _dbset.where(predicate);
return data.firstordefault();
}
public async task<tentity> getasync(tkey id)
{
if (id == null)
{
return default(tentity);
}
return await _dbset.findasync(id);
}
public async task<tentity> getasync(expression<func<tentity, bool>> predicate = null, bool isnotracking = true)
{
var data = isnotracking ? _dbset.where(predicate).asnotracking() : _dbset.where(predicate);
return await data.firstordefaultasync();
}
public async task<list<tentity>> getlistasync(expression<func<tentity, bool>> predicate = null, string ordering = "", bool isnotracking = true)
{
var data = isnotracking ? _dbset.where(predicate).asnotracking() : _dbset.where(predicate);
if (!string.isnullorempty(ordering))
{
data = data.orderbybatch(ordering);
}
return await data.tolistasync();
}
public list<tentity> getlist(expression<func<tentity, bool>> predicate = null, string ordering = "", bool isnotracking = true)
{
var data = isnotracking ? _dbset.where(predicate).asnotracking() : _dbset.where(predicate);
if (!string.isnullorempty(ordering))
{
data = data.orderbybatch(ordering);
}
return data.tolist();
}
public async task<iqueryable<tentity>> loadasync(expression<func<tentity, bool>> predicate = null, bool isnotracking = true)
{
if (predicate == null)
{
predicate = c => true;
}
return await task.run(() => isnotracking ? _dbset.where(predicate).asnotracking() : _dbset.where(predicate));
}
public iqueryable<tentity> load(expression<func<tentity, bool>> predicate = null, bool isnotracking = true)
{
if (predicate == null)
{
predicate = c => true;
}
return isnotracking ? _dbset.where(predicate).asnotracking() : _dbset.where(predicate);
}
#endregion
#region sql语句
public virtual void bulkinsert<t>(list<t> entities)
{ }
public int executesql(string sql)
{
return _dbcontext.database.executesqlcommand(sql) ; 
}
public task<int> executesqlasync(string sql)
{
return _dbcontext.database.executesqlcommandasync(sql);  
}
public int executesql(string sql, list<dbparameter> splist)
{
return  _dbcontext.database.executesqlcommand(sql, splist.toarray());
}
public task<int>  executesqlasync(string sql, list<dbparameter> splist)
{   
return  _dbcontext.database.executesqlcommandasync(sql, splist.toarray());
}
public virtual datatable getdatatablewithsql(string sql)
{
throw new notimplementedexception();
}
public virtual datatable getdatatablewithsql(string sql, list<dbparameter> splist)
{
throw new notimplementedexception();
}
#endregion

  三、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
}

  引用了http://www.cnblogs.com/coldairarrow/p/9626691.html该框架设计思想及部分代码