项目使用Entity Framework用到的公共操作方法基类(Repository)及其使用 (转载)

转自:http://www.cnblogs.com/jelea/archive/2013/01/06/2848309.html

在项目中会有很多常用的操作方法如添加、删除、修改等,而在使用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<TEntity> : 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         /// <summary>
 21         /// 获得提供用于查询和使用对象形式的实体数据功能
 22         /// </summary>
 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         /// <summary>
 44         /// 实体名字
 45         /// </summary>
 46         public string EntitySetName
 47         {
 48             get { return this.entitySetName; }
 49         }
 50         /// <summary>
 51         /// 主键字段名
 52         /// </summary>
 53         public string KeyProperty
 54         {
 55             get { return this.keyProperty; }
 56         }
 57         /// <summary>
 58         /// 主键字段类型
 59         /// </summary>
 60         public string KeyPropertyType
 61         {
 62             get { return this.keyPropertyType; }
 63         }
 64         #endregion
 65 
 66         #region objectContext
 67         /// <summary>
 68         /// 
 69         /// </summary>
 70         public Repository()
 71             : this(null)
 72         {
 73         }
 74         /// <summary>
 75         /// 用指定上下文构造新的实例
 76         /// </summary>
 77         /// <param name="objectContext">特定的上下文实例</param>
 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         /// <summary>
106         /// 释放对象上下文使用的资源
107         /// </summary>
108         public void Dispose()
109         {
110             CloseObjectContext();
111         }
112         /// <summary>
113         /// 释放ObjectContext连接
114         /// </summary>
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         #endregion
127 
128         #region Find 条件表达式查询
129         /// <summary>
130         /// 所有数据的查询列表
131         /// </summary>
132         /// <returns></returns>
133         public IQueryable<TEntity> FindAll()
134         {
135             return objectContext.CreateObjectSet<TEntity>().AsQueryable();
136         }
137 
138         /// <summary>
139         /// 根据指定条件表达式得到数据查询列表
140         /// </summary>
141         /// <param name="exp">条件表达式</param>
142         /// <returns></returns>
143         public IQueryable<TEntity> FindAll(Expression<Func<TEntity, bool>> exp)
144         {
145             return objectContext.CreateObjectSet<TEntity>().Where(exp);
146         }
147 
148         /// <summary>
149         /// 根据指定条件表达式得到数据实体
150         /// </summary>
151         /// <param name="exp">条件表达式</param>
152         /// <returns></returns>
153         public TEntity Find(Expression<Func<TEntity, bool>> exp)
154         {
155             return objectContext.CreateObjectSet<TEntity>().FirstOrDefault(exp);
156         }
157         #endregion
158 
159         #region GetQuery ESQL查询
160         /// <summary>
161         /// ESQL查询
162         /// </summary>
163         /// <param name="query">ESQL语句</param>
164         /// <param name="parameter">参数(可选)</param>
165         /// <returns></returns>
166         ///  <remarks>可用.Execute(MergeOption.AppendOnly)执行查询</remarks>
167         public ObjectQuery<TEntity> GetQuery(string query, params ObjectParameter[] parameter)
168         {
169             return objectContext.CreateQuery<TEntity>(query, parameter);
170         }
171 
172         /// <summary>
173         /// ESQL查询列表
174         /// </summary>
175         /// <param name="query">ESQL语句</param>
176         /// <param name="parameter">参数(可选)</param>
177         /// <returns></returns>
178         ///  <remarks>可用.Execute(MergeOption.AppendOnly)执行查询</remarks>
179         public List<TEntity> GetListByQuery(string query, params ObjectParameter[] parameter)
180         {
181             return objectContext.CreateQuery<TEntity>(query, parameter).ToList();
182         }
183         /// <summary>
184         /// ESQL查询
185         /// </summary>
186         /// <param name="query">ESQL语句</param>
187         /// <param name="parameter">参数(可选)</param>
188         /// <returns></returns>
189         /// <remarks>可用.Execute(MergeOption.AppendOnly)执行查询</remarks>
190         public ObjectQuery<Object> GetObjectQuery(string query, params ObjectParameter[] parameter)
191         {
192             return objectContext.CreateQuery<Object>(query, parameter);
193         }
194         /// <summary>
195         /// ESQL查询,返回单值Object
196         /// </summary>
197         /// <param name="query">ESQL语句</param>
198         /// <param name="parameter">参数(可选)</param>
199         /// <returns></returns>
200         /// <remarks>用.Execute(MergeOption.AppendOnly)查询</remarks>
201         public Object GetObjectByQuery(string query, params ObjectParameter[] parameter)
202         {
203             return GetObjectQuery(query, parameter).Execute(MergeOption.AppendOnly).FirstOrDefault();
204         }
205         #endregion
206 
207         #region GetList 返回List列表
208         /// <summary>
209         /// 所有数据列表
210         /// </summary>
211         /// <returns></returns>
212         public List<TEntity> GetList()
213         {
214             return objectContext.CreateObjectSet<TEntity>().AsQueryable().ToList();
215         }
216 
217         /// <summary>
218         /// 根据指定表达式得到数据列表
219         /// </summary>
220         /// <returns></returns>
221         public List<TEntity> GetList(Expression<Func<TEntity, bool>> exp)
222         {
223             return objectContext.CreateObjectSet<TEntity>().Where(exp).ToList();
224         }
225 
226         #endregion
227 
228         #region Add 添加实体数据
229         /// <summary>
230         /// 添加实体数据
231         /// </summary>
232         /// <param name="entity">实体</param>
233         public int Add(TEntity entity)
234         {
235             objectContext.CreateObjectSet<TEntity>().AddObject(entity);
236             return objectContext.SaveChanges();
237         }
238         /// <summary>
239         /// 添加实体数据
240         /// </summary>
241         /// <param name="entity">实体</param>
242         /// <param name="options">SaveOptions:
243         /// AcceptAllChangesAfterSave:把数据保存到数据库以后重置实体的状态。
244         /// DetectChangesBeforeSave:把数据保存到数据库之前同步实体的状态。
245         /// None:把数据保存到数据库之前,不同步实体的状态;把数据保存到数据库以后,也不重置实体的状态。
246         /// </param>
247         public int Add(TEntity entity, SaveOptions options)
248         {
249             objectContext.CreateObjectSet<TEntity>().AddObject(entity);
250             return objectContext.SaveChanges(options);
251         }
252 
253         /// <summary>
254         /// 批量添加实体数据
255         /// </summary>
256         /// <param name="entitys">实体列表</param>
257         public int AddAll(IEnumerable<TEntity> entitys)
258         {
259             foreach (var entity in entitys)
260             {
261                 objectContext.CreateObjectSet<TEntity>().AddObject(entity);
262             }
263             return objectContext.SaveChanges();
264         }
265         /// <summary>
266         /// 批量添加实体数据
267         /// </summary>
268         /// <param name="entitys">实体列表</param>
269         /// <param name="options">SaveOptions:
270         /// AcceptAllChangesAfterSave:把数据保存到数据库以后重置实体的状态。
271         /// DetectChangesBeforeSave:把数据保存到数据库之前同步实体的状态。
272         /// None:把数据保存到数据库之前,不同步实体的状态;把数据保存到数据库以后,也不重置实体的状态。
273         /// </param>
274         public int AddAll(IEnumerable<TEntity> entitys, SaveOptions options)
275         {
276             var objSet = objectContext.CreateObjectSet<TEntity>();
277             foreach (var entity in entitys)
278             {
279                 objSet.AddObject(entity);
280             }
281             return objectContext.SaveChanges(options);
282         }
283         #endregion
284 
285         #region Delete 删除实体数据
286         /// <summary>
287         /// 删除实体数据
288         /// </summary>
289         /// <param name="entity">实体</param>
290         public int Delete(TEntity entity)
291         {
292             objectContext.CreateObjectSet<TEntity>().DeleteObject(entity);
293             return objectContext.SaveChanges();
294         }
295 
296         /// <summary>
297         /// 批量删除实体数据
298         /// </summary>
299         /// <param name="entitys">实体列表</param>
300         public int DeleteAll(IEnumerable<TEntity> entitys)
301         {
302             if (entitys != null && entitys.Count() > 0)
303             {
304                 foreach (var entity in entitys)
305                 {
306                     objectContext.CreateObjectSet<TEntity>().DeleteObject(entity);
307                 }
308                 return objectContext.SaveChanges();
309             }
310             return 0;
311         }
312         #endregion
313 
314         #region Save 保存实体
315         /// <summary>
316         /// 保存实体和变动
317         /// </summary>        
318         /// <returns></returns>
319         public int Save()
320         {
321             return objectContext.SaveChanges();
322         }
323         /// <summary>
324         /// 保存实体和变动
325         /// </summary>    
326         /// <param name="options">SaveOptions:
327         /// AcceptAllChangesAfterSave:把数据保存到数据库以后重置实体的状态。
328         /// DetectChangesBeforeSave:把数据保存到数据库之前同步实体的状态。
329         /// None:把数据保存到数据库之前,不同步实体的状态;把数据保存到数据库以后,也不重置实体的状态。
330         /// </param>
331         public int Save(SaveOptions options)
332         {
333             return objectContext.SaveChanges(options);
334         }
335         /// <summary>
336         /// 保存指定的实体变动
337         /// </summary>        
338         /// <param name="entity">实体列表</param>
339         /// <returns></returns>
340         public int Save(TEntity entity)
341         {
342             objectContext.AttachTo(this.entitySetName, entity);
343             objectContext.SetAllModified(entity);
344             return objectContext.SaveChanges();
345         }
346         /// <summary>
347         /// 保存指定的实体变动
348         /// </summary>        
349         /// <param name="entity">实体列表</param>
350         /// <param name="options">SaveOptions:
351         /// AcceptAllChangesAfterSave:把数据保存到数据库以后重置实体的状态。
352         /// DetectChangesBeforeSave:把数据保存到数据库之前同步实体的状态。
353         /// None:把数据保存到数据库之前,不同步实体的状态;把数据保存到数据库以后,也不重置实体的状态。
354         /// </param>
355         public int Save(TEntity entity, SaveOptions options)
356         {
357             objectContext.AttachTo(this.entitySetName, entity);
358             objectContext.SetAllModified(entity);
359             return objectContext.SaveChanges(options);
360         }
361         #endregion
362 
363         /// <summary>
364         /// 将对象或对象图附加到本实体集中的对象上下文。
365         /// </summary>
366         /// <param name="entity"> 要附加的 System.Object。</param>
367         public void AttachTo(TEntity entity)
368         {
369             objectContext.AttachTo(this.entitySetName, entity);
370         }
371         /// <summary>
372         /// 将对象或对象图附加到特定实体集中的对象上下文。
373         /// </summary>
374         /// <param name="entitySetName"> 表示实体集名称,可以选择通过实体容器名称对它进行限定。</param>
375         /// <param name="entity"> 要附加的 System.Object。</param>
376         public void AttachTo(string entitySetName, TEntity entity)
377         {
378             objectContext.AttachTo(entitySetName, entity);
379         }
380         /// <summary>
381         /// 在对象具有实体键时将对象或对象图附加到对象上下文。
382         /// </summary>
383         /// <param name="entity">要附加的对象。</param>
384         public void Attach(System.Data.Objects.DataClasses.IEntityWithKey entity)
385         {
386             objectContext.Attach(entity);
387         }
388         /// <summary>
389         /// 从对象上下文移除对象。
390         /// </summary>
391         /// <param name="entity">要分离的对象。仅移除 entity;如果有任何相关对象受同一 System.Data.Objects.ObjectStateManager 跟踪,则不会自动分离这些对象。</param>
392         public void Detach(object entity)
393         {
394             objectContext.Detach(entity);
395         }
396 
397         #region ExecuteforStore 直接执行数据源语句,如MSSQL、Oracle
398         /// <summary>
399         /// 执行数据源语句(如MSSQL),返回影响的行数
400         /// </summary>
401         /// <param name="commandText">查询语句</param>
402         /// <param name="parameter">参数(可选)</param>
403         /// <returns></returns>
404         public int ExecuteStoreCommand(string commandText, params ObjectParameter[] parameter)
405         {
406             if (string.IsNullOrEmpty(commandText))
407             {
408                 return 0;
409             }
410             return objectContext.ExecuteStoreCommand(commandText, parameter);
411         }
412 
413         /// <summary>
414         /// 执行数据源查询语句(如MSSQL),获得数据查询列表
415         /// </summary>
416         /// <param name="commandText">查询语句</param>
417         /// <param name="parameter">参数(可选)</param>
418         /// <returns></returns>
419         public ObjectResult<TEntity> ExecuteStoreQuery(string commandText, params ObjectParameter[] parameter)
420         {
421             return objectContext.ExecuteStoreQuery<TEntity>(commandText, parameter);
422         }
423 
424         /// <summary>
425         /// 执行数据源的函数或存储过程,返回影响的行数
426         /// </summary>
427         /// <param name="functionName">函数或存储过程</param>
428         /// <param name="parameter">参数(可选)</param>
429         /// <returns></returns>
430         public int ExecuteFunction(string functionName, params ObjectParameter[] parameter)
431         {
432             if (string.IsNullOrEmpty(functionName))
433             {
434                 return 0;
435             }
436             return objectContext.ExecuteFunction(functionName, parameter);
437         }
438 
439         /// <summary>
440         /// 执行数据源的查询函数或存储过程,获得数据查询列表
441         /// </summary>
442         /// <param name="functionName">函数或存储过程</param>
443         /// <param name="parameter">参数(可选)</param>
444         /// <returns></returns>
445         public ObjectResult<TEntity> ExecuteFunctionQuery(string functionName, params ObjectParameter[] parameter)
446         {
447             return objectContext.ExecuteFunction<TEntity>(functionName, parameter);
448         }
449 
450         /// <summary>
451         /// 执行数据源语句(如MSSQL),获得得数据列表
452         /// </summary>
453         /// <param name="commandText">查询语句</param>
454         /// <param name="parameter">参数(可选)</param>
455         /// <returns></returns>
456         public List<TEntity> GetListByStoreQuery(string commandText, params ObjectParameter[] parameter)
457         {
458             return objectContext.ExecuteStoreQuery<TEntity>(commandText, parameter).ToList();
459         }
460         /// <summary>
461         /// 执行数据源的查询函数或存储过程,获得数据列表
462         /// </summary>
463         /// <param name="functionName">函数或存储过程</param>
464         /// <param name="parameter">参数(可选)</param>
465         /// <returns></returns>
466         public List<TEntity> GetListByFunction(string functionName, params ObjectParameter[] parameter)
467         {
468             return objectContext.ExecuteFunction<TEntity>(functionName, parameter).ToList();
469         }
470         #endregion
471 
472         #region ByID 对主键相关操作
473         /// <summary>
474         /// 获得指定主键的实体
475         /// </summary>
476         /// <param name="id">主键值</param>
477         /// <returns></returns>
478         public virtual TEntity GetByID(object id)
479         {
480             EntityKey ek = new EntityKey(objectContext.DefaultContainerName + "." + this.entitySetName, this.keyProperty, id);
481             object entity = null;
482             objectContext.TryGetObjectByKey(ek, out entity);
483             return (entity as TEntity);
484         }
485 
486         /// <summary>
487         /// 获得指定主键的实体列表
488         /// </summary>
489         /// <param name="ids">用逗号(,)分隔的主键ID</param>
490         /// <returns></returns>
491         public virtual List<TEntity> GetListByIDs(string ids)
492         {
493             ids = SqlFilter(ids);
494             if ("string".Equals(this.keyPropertyType, StringComparison.OrdinalIgnoreCase))
495             {
496                 ids = "'" + ids.Replace(",", "','") + "'";
497             }
498             string query = "select value it from " + this.entitySetName + " as it where it." + this.keyProperty + " in {" + ids + "}";
499             return objectContext.CreateQuery<TEntity>(query).ToList();
500         }
501         /// <summary>
502         /// 获得指定主键的实体列表
503         /// </summary>
504         /// <param name="ids">主键ID列表</param>
505         /// <returns></returns>
506         public virtual List<TEntity> GetListByIDs(IEnumerable<object> ids)
507         {
508             string strIDs = string.Empty;
509             foreach (int id in ids)
510             {
511                 strIDs += "," + id.ToString();
512             }
513             if (strIDs.Length > 1)
514             {
515                 strIDs = strIDs.Substring(1);
516             }
517             return GetListByIDs(strIDs);
518         }
519 
520         /// <summary>
521         /// 删除指定ID的实体。
522         /// 注意:此处直接执行数据源语句
523         /// </summary>
524         /// <param name="ids">用逗号(,)分隔的主键ID</param>
525         /// <returns></returns>
526         public virtual int DeleteByIDs(string ids)
527         {
528             if (string.IsNullOrEmpty(ids))
529             {
530                 return 0;
531             }
532             ids = SqlFilter(ids);
533             if ("string".Equals(this.keyPropertyType, StringComparison.OrdinalIgnoreCase))
534             {
535                 ids = "'" + ids.Replace(",", "','") + "'";
536             }
537             string sql = string.Format("delete {0}  where {1} in({2})", this.entitySetName, this.keyProperty, ids);
538             return ExecuteStoreCommand(sql);
539         }
540 
541         /// <summary>
542         /// 删除指定ID组的实体
543         /// </summary>
544         /// <param name="ids">主键ID列表</param>
545         /// <returns></returns>
546         public virtual int DeleteByIDs(IEnumerable<object> ids)
547         {
548             string strIDs = string.Empty;
549             foreach (int id in ids)
550             {
551                 strIDs += "," + id.ToString();
552             }
553             if (strIDs.Length > 1)
554             {
555                 strIDs = strIDs.Substring(1);
556             }
557             return DeleteByIDs(strIDs);
558         }
559         #endregion
560 
561         #region 事务
562         /// <summary>
563         /// TransactionScope事务处理。
564         /// TransactionScopeOption 默认值为 Required。
565         /// 用 .Complete() 提交事务
566         /// </summary>
567         /// <returns>返回 TransactionScope</returns>        
568         public TransactionScope GetTransactionScope()
569         {
570             return (new TransactionScope(TransactionScopeOption.Required));
571         }
572         /// <summary>
573         /// TransactionScope事务处理。
574         /// 用 .Complete() 提交事务
575         /// </summary>
576         /// <param name="scopeOption">提供用于创建事务范围的附加选项:
577         /// Required:该范围需要一个事务。如果已经存在环境事务,则使用该环境事务。否则,在进入范围之前创建新的事务。这是默认值。 
578         /// RequiresNew:总是为该范围创建新事务。 
579         /// Suppress:环境事务上下文在创建范围时被取消。范围中的所有操作都在无环境事务上下文的情况下完成。 
580         /// </param>
581         /// <returns>返回 TransactionScope</returns>
582         public TransactionScope GetTransactionScope(TransactionScopeOption scopeOption)
583         {
584             return (new TransactionScope(scopeOption));
585         }
586         /// <summary>
587         /// TransactionScope事务处理。
588         /// 用 .Complete() 提交事务
589         /// </summary>
590         /// <param name="scopeOption">提供用于创建事务范围的附加选项:
591         /// Required:该范围需要一个事务。如果已经存在环境事务,则使用该环境事务。否则,在进入范围之前创建新的事务。这是默认值。 
592         /// RequiresNew:总是为该范围创建新事务。 
593         /// Suppress:环境事务上下文在创建范围时被取消。范围中的所有操作都在无环境事务上下文的情况下完成。 
594         /// </param>
595         /// <param name="scopeTimeout">在它之后,事务范围将超时并中止此事务。</param>
596         /// <returns>返回 TransactionScope</returns> 
597         public TransactionScope GetTransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout)
598         {
599             return (new TransactionScope(scopeOption, scopeTimeout));
600         }
601 
602         /// <summary>
603         /// TransactionScope事务处理。
604         /// 用 .Complete() 提交事务
605         /// </summary>
606         /// <param name="transactionToUse">要设置为环境事务(以便该范围中进行的事务性工作使用此事务)的事务。</param>
607         /// <returns>返回 TransactionScope</returns> 
608         public TransactionScope GetTransactionScope(Transaction transactionToUse)
609         {
610             return (new TransactionScope(transactionToUse));
611         }
612         /// <summary>
613         /// TransactionScope事务处理。
614         /// 用 .Complete() 提交事务
615         /// </summary>
616         /// <param name="transactionToUse">要设置为环境事务(以便该范围中进行的事务性工作使用此事务)的事务。</param>
617         /// <param name="scopeTimeout">在它之后,事务范围将超时并中止此事务。</param>
618         /// <returns>返回 TransactionScope</returns> 
619         public TransactionScope GetTransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout)
620         {
621             return (new TransactionScope(transactionToUse, scopeTimeout));
622         }
623 
624         /// <summary>
625         /// TransactionScope事务处理。
626         /// 用 .Complete() 提交事务
627         /// </summary>
628         /// <param name="scopeOption">提供用于创建事务范围的附加选项:
629         /// Required:该范围需要一个事务。如果已经存在环境事务,则使用该环境事务。否则,在进入范围之前创建新的事务。这是默认值。 
630         /// RequiresNew:总是为该范围创建新事务。 
631         /// Suppress:环境事务上下文在创建范围时被取消。范围中的所有操作都在无环境事务上下文的情况下完成。 
632         /// </param>
633         /// <param name="transactionOptions">包含指定事务行为的附加信息。</param>
634         /// <returns>返回 TransactionScope</returns> 
635         public TransactionScope GetTransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions)
636         {
637             return (new TransactionScope(scopeOption, transactionOptions));
638         }        
639 
640         #endregion
641 
642         #region 辅助方法
643         /// <summary>
644         /// sql注入过滤
645         /// </summary>
646         /// <param name="sqlString"></param>
647         /// <returns></returns>
648         public string SqlFilter(string sqlString)
649         {
650             return sqlString
651                 .Replace("'", "''");
652         }
653         #endregion
654     }
655 
656 }
复制代码

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     /// <summary>
 8     /// ObjectContext扩展
 9     /// </summary>
10     public static class ObjectContextExtension
11     {
12         /// <summary>
13         /// 把所有属性都标为已修改
14         /// </summary>
15         /// <param name="objectContext"></param>
16         /// <param name="item"></param>
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<TEntity> : Repository<TEntity> 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         /// <summary>
12         /// 为其它Service指定与本Service相同的ObjContext数据对象
13         /// </summary>
14         /// <param name="newService">目标Service</param>
15         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 : BaseService<Department>
2 {
3 }


(完)

原文地址:https://www.cnblogs.com/zcm123/p/2918398.html