转自:
在项目中会有很多常用的操作方法如添加、删除、修改等,而在使用EF时虽然已是ORM,但仍然会习惯性的在业务层写大量类似方法,为此,分享一个我在项目使用的公共基类,经过多次修改,已在mssql和oracle数据库项目上使用没问题。希望对使用EF开发项目的朋友有帮助,不是说写的有多好,只是为了分享,因为我在使用EF之初也一直在找这样一个类但资源很少。 欢迎拍砖,不要伤人就行。。。
以下是 Repository.cs源码 :
Repository.cs
1 using System.Collections.Generic; 2 using System.Linq; 3 using System.Linq.Expressions; 4 using System.Data.Objects; 5 using System.Data.Common; 6 using System.Transactions; 7 8 namespace System.Data.Entity 9 { 10 public class Repository: IDisposable where TEntity : class 11 { 12 #region 私有属性 13 private ObjectContext objectContext; 14 private string entitySetName; 15 private string keyProperty = "ID"; 16 private string keyPropertyType = "Int32"; 17 #endregion 18 19 #region 公共属性 20 /// 21 /// 获得提供用于查询和使用对象形式的实体数据功能 22 /// 23 protected ObjectContext ObjContext 24 { 25 get 26 { 27 if (this.objectContext == null) 28 { 29 throw new Exception("数据库对象为空"); 30 } 31 if (this.objectContext.Connection.State == System.Data.ConnectionState.Closed) 32 { 33 this.objectContext.Connection.Open(); //如果关闭则打开 34 } 35 return this.objectContext; 36 } 37 set 38 { 39 this.objectContext = value; 40 objectContext.MetadataWorkspace.LoadFromAssembly(typeof(TEntity).Assembly); 41 } 42 } 43 ///44 /// 实体名字 45 /// 46 public string EntitySetName 47 { 48 get { return this.entitySetName; } 49 } 50 ///51 /// 主键字段名 52 /// 53 public string KeyProperty 54 { 55 get { return this.keyProperty; } 56 } 57 ///58 /// 主键字段类型 59 /// 60 public string KeyPropertyType 61 { 62 get { return this.keyPropertyType; } 63 } 64 #endregion 65 66 #region objectContext 67 ///68 /// 69 /// 70 public Repository() 71 : this(null) 72 { 73 } 74 ///75 /// 用指定上下文构造新的实例 76 /// 77 /// 特定的上下文实例 78 public Repository(ObjectContext objectContext) 79 { 80 if (objectContext != null) //也可以构造后再指定数据库 81 { 82 this.objectContext = objectContext; //指定数据库 83 } 84 85 Type entityType = typeof(TEntity); 86 //表名 87 this.entitySetName = entityType.Name; 88 //主键 89 foreach (var prop in entityType.GetProperties()) 90 { 91 var attr = prop.GetCustomAttributes(typeof(System.Data.Objects.DataClasses.EdmScalarPropertyAttribute), false).FirstOrDefault() as System.Data.Objects.DataClasses.EdmScalarPropertyAttribute; 92 if (attr != null && attr.EntityKeyProperty) 93 { 94 this.keyProperty = prop.Name; 95 this.keyPropertyType = prop.PropertyType.Name; 96 break; 97 } 98 } 99 100 if (objectContext != null)101 {102 objectContext.MetadataWorkspace.LoadFromAssembly(typeof(TEntity).Assembly);103 }104 }105 ///106 /// 释放对象上下文使用的资源107 /// 108 public void Dispose()109 {110 CloseObjectContext();111 }112 ///113 /// 释放ObjectContext连接114 /// 115 public void CloseObjectContext()116 {117 if (objectContext != null )118 {119 if (objectContext.Connection.State == ConnectionState.Open)120 {121 objectContext.Connection.Close();122 }123 objectContext.Dispose();124 }125 }126 #endregion127 128 #region Find 条件表达式查询129 ///130 /// 所有数据的查询列表131 /// 132 ///133 public IQueryable FindAll()134 {135 return objectContext.CreateObjectSet ().AsQueryable();136 }137 138 /// 139 /// 根据指定条件表达式得到数据查询列表140 /// 141 /// 条件表达式142 ///143 public IQueryable FindAll(Expression > exp)144 {145 return objectContext.CreateObjectSet ().Where(exp);146 }147 148 /// 149 /// 根据指定条件表达式得到数据实体150 /// 151 /// 条件表达式152 ///153 public TEntity Find(Expression > exp)154 {155 return objectContext.CreateObjectSet ().FirstOrDefault(exp);156 }157 #endregion158 159 #region GetQuery ESQL查询160 /// 161 /// ESQL查询162 /// 163 /// ESQL语句164 /// 参数(可选)165 ///166 /// 可用.Execute(MergeOption.AppendOnly)执行查询 167 public ObjectQueryGetQuery(string query, params ObjectParameter[] parameter)168 {169 return objectContext.CreateQuery (query, parameter);170 }171 172 /// 173 /// ESQL查询列表174 /// 175 /// ESQL语句176 /// 参数(可选)177 ///178 /// 可用.Execute(MergeOption.AppendOnly)执行查询 179 public ListGetListByQuery(string query, params ObjectParameter[] parameter)180 {181 return objectContext.CreateQuery (query, parameter).ToList();182 }183 /// 184 /// ESQL查询185 /// 186 /// ESQL语句187 /// 参数(可选)188 ///189 /// 可用.Execute(MergeOption.AppendOnly)执行查询 190 public ObjectQuery
ObjectContext扩展类ObjectContextExtension.cs
ObjectContextExtension.cs
1 using System.Linq; 2 using System.Data.Objects; 3 using System.Collections; 4 5 namespace System.Data.Objects 6 { 7 ///8 /// ObjectContext扩展 9 /// 10 public static class ObjectContextExtension11 {12 ///13 /// 把所有属性都标为已修改14 /// 15 /// 16 /// 17 public static void SetAllModified(this ObjectContext objectContext, object item)18 {19 ObjectStateEntry stateEntry = objectContext.ObjectStateManager.GetObjectStateEntry(item) as ObjectStateEntry;20 IEnumerable propertyNameList = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(pn => pn.FieldType.Name);21 foreach (string propName in propertyNameList)22 {23 stateEntry.SetModifiedProperty(propName);24 }25 stateEntry.SetModified();26 }27 }28 }
使用上可以用以下结构:
1. 建一个base业务类,代码如下: BaseService.cs
1 public class BaseService: Repository where TEntity : System.Data.Objects.DataClasses.EntityObject //或用class 2 { 3 public BaseService() 4 : base(new OA.Data.OAEntities())//默认数据库 5 { 6 } 7 public BaseService(System.Data.Objects.ObjectContext objContext) 8 : base(objContext) 9 {10 }11 /// 12 /// 为其它Service指定与本Service相同的ObjContext数据对象13 /// 14 /// 目标Service15 protected dynamic SameObjContext(dynamic service)16 {17 service.ObjContext = this.ObjContext;18 return service;19 }20 }
2.业务层的每个业务类都继承BaseService,如针对Department的业务层DepartmentService.cs代码:
DepartmentService.cs
(完) 1 public class DepartmentService : BaseService2 {3 }