不鸣则已

海阔凭鱼跃,天高任鸟飞!

首页 新随笔 联系 订阅 管理
 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 }
BaseDAL
 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 }
DbContextFactory

 

posted on 2014-06-17 13:36  唐群  阅读(385)  评论(0编辑  收藏  举报