/// <summary>
/// MSSQL数据库 数据层 父类
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseDAL<T> : IDAL.IBaseDAL<T> where T : class, new()
{
MODEL.OuOAEntities db = new MODEL.OuOAEntities();
public int Add(T model)
{
db.Set<T>().Add(model);
return db.SaveChanges();
}
public int DeleteBy(T model)
{
db.Set<T>().Attach(model); //附加到EF容器
db.Set<T>().Remove(model); //标识为删除状态
return db.SaveChanges();
}
public int DeleteBy(Expression<Func<T, bool>> whereLambda)
{
//1.查询出要删除的数据
List<T> listDel = db.Set<T>().Where(whereLambda).ToList();
//2.将要删除的数据用删除方法添加到EF容器中
listDel.ForEach(u =>
{
db.Set<T>().Attach(u);
db.Set<T>().Remove(u);
});
//3.一次性删除savechanges()
return db.SaveChanges();
}
public List<T> GetListBy(Expression<Func<T, bool>> whereLambda)
{
return db.Set<T>().Where(whereLambda).ToList();
}
public List<T> GetListBy<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderbyLambda)
{
return db.Set<T>().Where(whereLambda).OrderBy(orderbyLambda).ToList();
}
public List<T> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> orderbyLambda)
{
int count = (pageIndex - 1) * pageSize;
return db.Set<T>().Where(whereLambda).OrderBy(orderbyLambda).Skip(count).Take(pageSize).ToList();
}
public int Modify(T model, params string[] proNames)
{
DbEntityEntry entry = db.Entry<T>(model);
entry.State = System.Data.Entity.EntityState.Unchanged;
foreach (string per in proNames)
{
entry.Property(per).IsModified = true;
}
return db.SaveChanges();
}
public int ModifyBy(T model, Expression<Func<T, bool>> whereLambda, params string[] modifiedProNames)
{
List<T> list = db.Set<T>().Where(whereLambda).ToList();
//获取实体类 类型对象
Type t = typeof(T);
//获取实体类 所有的公共属性
List<PropertyInfo> proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
//创建实体属性字典集合
Dictionary<string, PropertyInfo> dic = new Dictionary<string, PropertyInfo>();
//将 实体属性 中要修改的属性名 添加到 字典集合中 健:属性名 值:属性对象
proInfos.ForEach(u =>
{
if(modifiedProNames.Contains(u.Name))
{
dic.Add(u.Name, u);
}
});
//循环要修改的属性名
foreach(string per in modifiedProNames)
{
//判断 要修改的属性名是否在 实体类的属性集合中存在
if (dic.ContainsKey(per))
{
//如果存在 则取出要修改的 属性对象
PropertyInfo proInfo = dic[per];
//取出要修改的值
object newValue = proInfo.GetValue(model, null);
//批量设置要修改到的对象的属性
foreach(T user in list)
{
//为 要修改的对象 的 要修改的属性 设置新的值
proInfo.SetValue(user, newValue, null);
}
}
}
return db.SaveChanges();
}
}