public class BaseServer
{
//上下文
private readonly DataContext Context;
protected LogServer LogServer { get; }
//依赖注入
protected BaseServer(DataContext dataContext, LogServer logServer)
{
this.Context = dataContext;
this.LogServer = logServer;
}
//查找全部
protected List<T> GetAll<T>() where T : class
{
return Context.Set<T>().ToList();
}
//根据主键查找
protected T GetDataByKey<T>(object key1, object key2, object key3) where T : class
{
return Context.Set<T>().Find(key1, key2, key3);
}
//根据Lambda表达式查找
protected IEnumerable<T> GetDataByLambda<T>(Expression<Func<T, bool>> whereLambda) where T : class
{
try
{
return Context.Set<T>().Where(whereLambda);
}
catch (Exception ex)
{
LogServer.LogErr(ex.ToString());
return null;
}
}
//修改数据
protected bool Update<T>(T newData) where T : class
{
try
{
Context.Set<T>().Attach(newData);
this.Context.Entry(newData).State = EntityState.Modified;
Context.SaveChanges();
return true;
}
catch (Exception ex)
{
LogServer.LogErr(ex.ToString());
return false;
}
}
//添加数据
protected bool Add<T>(IEnumerable<T> newData) where T : class
{
try
{
Context.Set<T>().AddRange(newData);
Context.SaveChanges();
return true;
}
catch (Exception ex)
{
LogServer.LogErr(ex.ToString());
return false;
}
}
//根据主键进行数据删除
protected bool RemoveByKey<T>(object key1, object key2, object key3) where T : class
{
try
{
var v = GetDataByKey<T>(key1, key2, key3);
Context.Set<T>().Remove(v);
Context.SaveChanges();
return true;
}
catch (Exception ex)
{
LogServer.LogErr(ex.ToString());
return false;
}
}
//添加数据
protected bool Add<T>(T newData) where T : class
{
try
{
Context.Set<T>().Add(newData);
Context.SaveChanges();
return true;
}
catch (Exception ex)
{
LogServer.LogErr(ex.ToString());
return false;
}
}
//查找数据根据sql
protected List<T> GetDataBySql<T>(string sql) where T :class
{
try
{
return Context.Set<T>().FromSql(sql).ToList();
}
catch (Exception ex)
{
LogServer.LogErr("GetDataBySql:" + ex.ToString());
return null;
}
}
//执行存储过程
protected bool RunProcedure(string sql)
{
try
{
Context.Database.ExecuteSqlCommand(sql);
return true;
}
catch (Exception ex)
{
LogServer.LogErr("RunProcedure:" + ex.ToString());
return false;
}
}
}
EF Core增删改查基类
最新推荐文章于 2024-05-20 15:54:37 发布