1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.Data.Entity;
7
8 namespace DAL
9 {
10
11 /// <summary>
12 /// 基于EF的通用访问类
13 /// </summary>
14 public class EFDBHelper
15 {
16 private DbContext dbContex = null;
17
18 public EFDBHelper(DbContext context)
19 {
20 this.dbContex = context;
21 }
22
23
24 /// <summary>
25 /// 新增实体
26 /// </summary>
27 /// <typeparam name="T"></typeparam>
28 /// <param name="entity"></param>
29 /// <returns></returns>
30 public int Add<T>(T entity) where T : class
31 {
32 dbContex.Entry<T>(entity).State = EntityState.Added;
33 //dbContex.Set<T>().Attach(entity);
34 //dbContex.Set<T>().Add(entity);
35 return dbContex.SaveChanges();
36 }
37
38 /// <summary>
39 /// 修改一个实体
40 /// </summary>
41 /// <typeparam name="T"></typeparam>
42 /// <param name="entity"></param>
43 /// <returns></returns>
44 public int Modify<T>(T entity) where T : class
45 {
46 dbContex.Entry<T>(entity).State = EntityState.Modified; //此种方式设置更新的是全部字段,不适合部分字段的更新
47 return dbContex.SaveChanges();
48 }
49
50 /// <summary>
51 ///删除一个实体
52 /// </summary>
53 /// <typeparam name="T"></typeparam>
54 /// <param name="entity"></param>
55 /// <returns></returns>
56
57 public int Delete<T>(T entity) where T : class
58 {
59 dbContex.Entry<T>(entity).State = EntityState.Deleted;
60 //dbContex.Set<T>().Attach(entity);
61 //dbContex.Set<T>().Remove(entity);
62 return dbContex.SaveChanges();
63 }
64 }
65 }