1 public class BaseDAL<T> where T : class,new() 2 { 3 protected DbContext dbContext = DbContextFactory.GetCurrentDbContext(); 4 5 protected DbSet<T> dbSet 6 { 7 get 8 { 9 return dbContext.Set<T>(); 10 } 11 } 12 13 protected bool SaveChanges() 14 { 15 return dbContext.SaveChanges() > 0; 16 } 17 18 protected T Add(T entity) 19 { 20 entity = dbSet.Attach(entity); 21 dbContext.Entry<T>(entity).State = EntityState.Added;//dbSet.Add(entity); 22 return entity; 23 } 24 25 protected void Delete(T entity) 26 { 27 dbContext.Entry<T>(entity).State = EntityState.Deleted; 28 } 29 30 protected void Update(T entity) 31 { 32 dbContext.Entry<T>(entity).State = EntityState.Modified; 33 } 34 35 protected T Select(Func<T, bool> whereLambda) 36 { 37 return dbSet.Where<T>(whereLambda).FirstOrDefault(); 38 } 39 40 protected List<T> SelectList(Func<T, bool> whereLambda) 41 { 42 return dbSet.Where<T>(whereLambda).ToList(); 43 } 44 45 protected List<T> SelectPageList<s>(int pageIndex, int pageSize, out int totalCount, Func<T, bool> whereLambda, Func<T, s> orderLambda, bool isAsc) 46 { 47 IEnumerable<T> enumerableList = dbSet.Where<T>(whereLambda); 48 totalCount = enumerableList.Count(); 49 if (isAsc) 50 { 51 enumerableList = dbSet.Where<T>(whereLambda).OrderBy<T, s>(orderLambda).Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize); 52 } 53 else 54 { 55 enumerableList = dbSet.Where<T>(whereLambda).OrderByDescending<T, s>(orderLambda).Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize); 56 } 57 return enumerableList.ToList(); 58 } 59 }
1 public class DbContextFactory 2 { 3 public static DbContext GetCurrentDbContext() 4 { 5 DbContext dbContext = (DbContext)CallContext.GetData("dbContext"); 6 if (dbContext == null) 7 { 8 dbContext = new jxcContext(); 9 CallContext.SetData("dbContext", dbContext); 10 } 11 return dbContext; 12 } 13 }
本文版权归作者和博客园共有,来源网址:http://www.cnblogs.com/tq1226112215/
欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。