public abstract class BaseDal<T> where T : class, new()
{
#region 查
public List<T> All()
{
using (var db = new DBEntities())
{
return db.Set<T>().ToList<T>();
}
}
public List<T> Query(Func<T, bool> func)
{
using (var db = new DBEntities())
{
return db.Set<T>().Where(func).ToList<T>();
}
}
#endregion
#region 增
public T Add(T entity)
{
using (var db = new DBEntities())
{
db.Entry(entity).State = EntityState.Added;
db.SaveChanges();
return entity;
}
}
public bool Add(List<T> entities)
{
using (var db = new DBEntities())
{
db.Entry(entities).State = EntityState.Added;
return db.SaveChanges() > 0;
}
}
#endregion
#region 删
public bool Del(T entity)
{
using (var db = new DBEntities())
{
db.Set<T>().Attach(entity);
db.Entry(entity).State = EntityState.Deleted;
return db.SaveChanges() > 0;
}
}
public bool Del(List<T> entities)
{
using (var db = new DBEntities())
{
foreach (var entity in entities)
{
db.Set<T>().Attach(entity);
db.Entry(entity).State = EntityState.Deleted;
}
return db.SaveChanges() > 0;
}
}
public bool Del(Func<T, bool> func)
{
using (var db = new DBEntities())
{
var entities = Query(func);
return Del(entities);
}
}
#endregion
#region 改
public bool Update(T entity)
{
using (var db = new DBEntities())
{
db.Set<T>().Attach(entity);
db.Entry(entity).State = EntityState.Modified;
return db.SaveChanges() > 0;
}
}
#endregion
}
C# EF通用DAL基类
最新推荐文章于 2024-09-10 19:43:39 发布