ORM框架 EF - code first 的封装

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ORM框架 EF - code first 的封装相关的知识,希望对你有一定的参考价值。

Code first 是Microsoft Entity Framework中的一种模式,CodeFirst不会有可视化的界面来进行拖动编辑DataBase-Entity,但会以一个类来进行对数据表关系的描述,以及对所有实体类的描述,优势在于,代码更加地简洁,文件目录更加清晰,也更加便于维护。

直接用实体关系类进行操作,最后SaveChanges,无可厚非,当然可以了,但是,对于一个追求更加简便,更加抽象的程序员来说,无限的封装似乎是一种追求吧,废话不多说,这里直接上EF_Helper_DG的代码->

首先示例性地来一个实体关系类,以便于后面的帮助类的对比,当然,这个类也是不可或缺的。

DBEntity_DG(习惯性地起名)

 1 namespace QX_Frame.DAL.Service
 2 {
 3     using System.Data.Entity;
 4     using QX_Frame.Model;
 5 
 6     public partial class DBEntity_DG : DbContext
 7     {
 8         public DBEntity_DG()
 9             : base("name=DBEntity_DG")
10         {
11         }
12 
13         public virtual DbSet<tb_Class> tb_Class { get; set; }
14         public virtual DbSet<tb_User> tb_User { get; set; }
15 
16         protected override void OnModelCreating(DbModelBuilder modelBuilder)
17         {
18             modelBuilder.Entity<tb_Class>()
19                 .Property(e => e.Name)
20                 .IsFixedLength();
21 
22             modelBuilder.Entity<tb_Class>()
23                 .HasMany(e => e.tb_User)
24                 .WithRequired(e => e.tb_Class)
25                 .HasForeignKey(e => e.ClassId)
26                 .WillCascadeOnDelete(false);
27 
28             modelBuilder.Entity<tb_User>()
29                 .Property(e => e.Name)
30                 .IsFixedLength();
31         }
32     }
33 }

然后,我们来上正菜 EF_DBEntity_DG

  1 using LinqKit; //AsExpandable() in linqkit.dll
  2 using System;
  3 using System.Collections.Generic;
  4 using System.IO;
  5 using System.Linq;
  6 using System.Linq.Expressions;
  7 using System.Data.Entity;
  8 using QX_Frame.Helper_DG_Framework_4_6;
  9 
 10 namespace QX_Frame.DAL.Service
 11 {
 12     /*  time:2016-10-30 15:26:05
 13         author:qixiao
 14           */
 15 
 16     #region The EF_DBEntity_DG visual Interface
 17 
 18     public interface IEF_DBEntity_DG
 19     {
 20         Boolean IsAdd<T>(T entity);
 21         Boolean IsAdd<T>(T entity, out T outEntity);
 22         Boolean IsAdd<T>(List<T> entities);
 23 
 24         Boolean IsUpdate<T>(T entity);
 25         Boolean IsUpdate<T>(T entity, out T outEntity);
 26 
 27         Boolean IsDelete<T>(T entity);
 28         Boolean IsDelete<T>(List<T> entities);
 29         Boolean IsDelete<T>(Expression<Func<T, bool>> deleteWhere);
 30 
 31         T selectSingle<T>(Expression<Func<T, Boolean>> selectWhere);
 32 
 33         List<T> selectAll<T>();
 34         List<T> selectAll<T>(out int Count);
 35         List<T> selectAll<T>(Expression<Func<T, T>> orderBy, Boolean isDESC = false);
 36         List<T> selectAll<T>(Expression<Func<T, T>> orderBy, out int Count, Boolean isDESC = false);
 37         List<T> selectAll<T>(Expression<Func<T, Boolean>> selectWhere);
 38         List<T> selectAll<T>(Expression<Func<T, Boolean>> selectWhere, out int Count);
 39         List<T> selectAll<T>(Expression<Func<T, Boolean>> selectWhere, Expression<Func<T, T>> orderBy, Boolean isDESC = false);
 40         List<T> selectAll<T>(Expression<Func<T, Boolean>> selectWhere, Expression<Func<T, T>> orderBy, out int Count, Boolean isDESC = false);
 41 
 42         List<T> selectAllPaging<T>(int pageIndex, int pageSize);
 43         List<T> selectAllPaging<T>(int pageIndex, int pageSize, out int Count);
 44         List<T> selectAllPaging<T>(int pageIndex, int pageSize, Expression<Func<T, Boolean>> selectWhere);
 45         List<T> selectAllPaging<T>(int pageIndex, int pageSize, Expression<Func<T, Boolean>> selectWhere, out int Count);
 46         List<T> selectAllPaging<T>(int pageIndex, int pageSize, Expression<Func<T, T>> orderBy, Boolean isDESC = false);
 47         List<T> selectAllPaging<T>(int pageIndex, int pageSize, Expression<Func<T, T>> orderBy, out int Count, Boolean isDESC = false);
 48         List<T> selectAllPaging<T>(int pageIndex, int pageSize, Expression<Func<T, Boolean>> selectWhere, Expression<Func<T, T>> orderBy, Boolean isDESC = false);
 49         List<T> selectAllPaging<T>(int pageIndex, int pageSize, Expression<Func<T, Boolean>> selectWhere, Expression<Func<T, T>> orderBy, out int Count, Boolean isDESC = false);
 50     }
 51 
 52     #endregion
 53 
 54     public abstract class EF_DBEntity_DG
 55     {
 56         /*the singleton DBEntity_DG */
 57         /// <summary>
 58         /// The DBEntity_DG is must be named: DBEntity_DG
 59         /// </summary>
 60         private volatile static DBEntity_DG db = null;
 61 
 62         #region The Singleton to new DBEntity_DG 
 63         private static readonly object lockHelper = new object();
 64         static EF_DBEntity_DG()
 65         {
 66             if (db == null)
 67             {
 68                 lock (lockHelper)
 69                 {
 70                     if (db == null)
 71                         db = new DBEntity_DG();
 72                 }
 73             }
 74             //close the Validate of EF OnSaveEnabled
 75             db.Configuration.ValidateOnSaveEnabled = false;
 76         }
 77         #endregion
 78 
 79         /// <summary>
 80         /// Give the Error Log support
 81         /// </summary>
 82         /// <param name="logText">LogText</param>
 83         /// <param name="isAppend">The Log Text isAppend or Cover</param>
 84         private static void Log_DG(string logText, string logTitle = "DBEntity_DG Error", Boolean isAppend = true)
 85         {
 86             string LogLocation_DG = @"Log_QX_Frame/Log_QX_Frame_Error/";
 87             try
 88             {
 89                 LogLocation_DG = Config_Helper_DG.AppSetting_Get("Log_Location_Error_DG");
 90             }
 91             catch (Exception)
 92             {
 93                 LogLocation_DG = @"Log_QX_Frame/Log_QX_Frame_Error/";
 94             }
 95             if (!Directory.Exists(LogLocation_DG))
 96             {
 97                 Directory.CreateDirectory(LogLocation_DG);
 98             }
 99             using (StreamWriter log = new StreamWriter(LogLocation_DG + "Log_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".Log", isAppend))
100             {
101                 log.WriteLine();
102                 log.WriteLine(DateTime_Helper_DG.Get_DateTime_Now_24HourType() + "   -------" + logTitle + " Log !--------------------");
103                 log.WriteLine();
104                 log.WriteLine(logText);
105             }
106         }
107 
108         #region Add 
109 
110         public static Boolean IsAdd<T>(T entity) where T : class
111         {
112             try
113             {
114                 db.Entry<T>(entity).State = EntityState.Added;
115                 return db.SaveChanges() > 0;
116             }
117             catch (Exception ex)
118             {
119                 Log_DG(ex.ToString());
120                 return false;
121             }
122         }
123         public static Boolean IsAdd<T>(T entity, out T outEntity) where T : class
124         {
125             try
126             {
127                 db.Entry<T>(entity).State = EntityState.Added;
128                 outEntity = entity;
129                 return db.SaveChanges() > 0;
130             }
131             catch (Exception ex)
132             {
133                 Log_DG(ex.ToString());
134                 outEntity = default(T);
135                 return false;
136             }
137         }
138         public static Boolean IsAdd<T>(List<T> entities) where T : class
139         {
140             try
141             {
142                 db.Set<T>().AddRange(entities);
143                 return db.SaveChanges() > 0;
144             }
145             catch (Exception ex)
146             {
147                 Log_DG(ex.ToString());
148                 return false;
149             }
150         }
151 
152         #endregion
153 
154         #region Update
155 
156         public static Boolean IsUpdate<T>(T entity) where T : class
157         {
158             try
159             {
160                 if (db.Entry<T>(entity).State == EntityState.Detached)
161                 {
162                     db.Set<T>().Attach(entity);
163                     db.Entry<T>(entity).State = EntityState.Modified;
164                 }
165                 return db.SaveChanges() > 0;
166             }
167             catch (Exception ex)
168             {
169                 Log_DG(ex.ToString());
170                 return false;
171             }
172         }
173         public static Boolean IsUpdate<T>(T entity, out T outEntity) where T : class
174         {
175             try
176             {
177                 db.Set<T>().Attach(entity);
178                 db.Entry<T>(entity).State = EntityState.Modified;
179                 outEntity = entity;
180                 return db.SaveChanges() > 0;
181             }
182             catch (Exception ex)
183             {
184                 Log_DG(ex.ToString());
185                 outEntity = default(T);
186                 return false;
187             }
188         }
189 
190         #endregion
191 
192         #region Delete
193 
194         public static Boolean IsDelete<T>(T entity) where T : class
195         {
196             try
197             {
198                 db.Set<T>().Attach(entity);
199                 db.Entry<T>(entity).State = EntityState.Deleted;
200                 return db.SaveChanges() > 0;
201             }
202             catch (Exception ex)
203             {
204                 Log_DG(ex.ToString());
205                 return false;
206             }
207         }
208         public static Boolean IsDelete<T>(List<T> entities) where T : class
209         {
210             try
211             {
212                 db.Set<T>().RemoveRange(entities);
213                 return db.SaveChanges() > 0;
214             }
215             catch (Exception ex)
216             {
217                 Log_DG(ex.ToString());
218                 return false;
219             }
220         }
221         public static Boolean IsDelete<T>(Expression<Func<T, bool>> deleteWhere) where T : class
222         {
223             try
224             {
225                 List<T> entitys = db.Set<T>().AsExpandable().Where(deleteWhere).ToList();
226                 entitys.ForEach(m => db.Entry<T>(m).State = EntityState.Deleted);
227                 return db.SaveChanges() > 0;
228             }
229             catch (Exception ex)
230             {
231                 Log_DG(ex.ToString());
232                 return false;
233             }
234         }
235         #endregion
236 
237         #region Select 
238 
239         public static Boolean IsExist<T>(Expression<Func<T, Boolean>> selectWhere) where T : class
240         {
241             try
242             {
243                 return db.Set<T>().AsExpandable().Where(selectWhere).ToList().FirstOrDefault<T>() == null ? false : true;
244             }
245             catch (Exception ex)
246             {
247                 Log_DG(ex.ToString());
248                 return default(Boolean);
249             }
250         }
251         public static T selectSingle<T>(Expression<Func<T, Boolean>> selectWhere) where T : class
252         {
253             try
254             {
255                 return db.Set<T>().AsExpandable().Where(selectWhere).ToList().FirstOrDefault<T>();
256             }
257             catch (Exception ex)
258             {
259                 Log_DG(ex.ToString());
260                 return default(T);
261             }
262         }
263         public static List<T> selectAll<T>() where T : class
264         {
265             try
266             {
267                 return db.Set<T>().AsExpandable().ToList();
268             }
269             catch (Exception ex)
270             {
271                 Log_DG(ex.ToString());
272                 return default(List<T>);
273             }
274         }
275         public static List<T> selectAll<T>(out int Count) where T : class
276         {
277             try
278             {
279                 Count = db.Set<T>().AsExpandable().Count();
280                 return db.Set<T>().AsExpandable().ToList();
281             }
282             catch (Exception ex)
283             {
284                 Log_DG(ex.ToString());
285                 Count = 0;
286                 return default(List<T>);
287             }
288         }
289         public static List<T> selectAll<T, TKey>(Expression<Func<T, TKey>> orderBy, Boolean isDESC = false) where T : class
290         {
291             try
292             {
293                 if (isDESC)
294                     return db.Set<T>().AsExpandable().OrderByDescending(orderBy).ToList();
295                 else
296                     return db.Set<T>().AsExpandable().OrderBy(orderBy).ToList();
297             }
298             catch (Exception ex)
299             {
300                 Log_DG(ex.ToString());
301                 return default(List<T>);
302             }
303         }
304         public static List<T> selectAll<T, TKey>(Expression<Func<T, TKey>> orderBy, out int Count, Boolean isDESC = false) where T : class
305         {
306             try
307             {
308                 Count = db.Set<T>().AsExpandable().Count();
309                 if (isDESC)
310                     return db.Set<T>().AsExpandable().OrderByDescending(orderBy).ToList();
311                 else
312                     return db.Set<T>().AsExpandable().OrderBy(orderBy).ToList();
313             }
314             catch (Exception ex)
315             {
316                 Log_DG(ex.ToString());
317                 Count = 0;
318                 return default(List<T>);
319             }
320         }
321         public static List<T> selectAll<T>(Expression<Func<T, Boolean>> selectWhere) where T : class
322         {
323             try
324             {
325                 return db.Set<T>().AsExpandable().Where(selectWhere).ToList();
326             }
327             catch (Exception ex)
328             {
329                 Log_DG(ex.ToString());
330                 return default(List<T>);
331             }
332         }
333         public static List<T> selectAll<T>(Expression<Func<T, Boolean>> selectWhere, out int Count) where T : class
334         {
335 
336             try
337             {
338                 var list = db.Set<T>().AsExpandable().Where(selectWhere);
339                 Count = list.Count();
340                 return list.ToList();
341             }
342             catch (Exception ex)
343             {
344                 Log_DG(ex.ToString());
345                 Count = 0;
346                 return default(List<T>);
347             }
348         }
349         public static List<T> selectAll<T, TKey>(Expression<Func<T, TKey>> orderBy, Expression<Func<T, Boolean>> selectWhere, Boolean isDESC = false) where T : class
350         {
351             try
352             {
353                 if (isDESC)
354                     return db.Set<T>().AsExpandable().Where(selectWhere).OrderByDescending(orderBy).ToList();
355                 else
356                     return db.Set<T>().AsExpandable().Where(selectWhere).OrderBy(orderBy).ToList();
357             }
358             catch (Exception ex)
359             {
360                 Log_DG(ex.ToString());
361                 return default(List<T>);
362             }
363         }
364         public static List<T> selectAll<T, TKey>(Expression<Func<T, TKey>> orderBy, Expression<Func<T, Boolean>> selectWhere, out int Count, Boolean isDESC = false) where T : class
365         {
366             try
367             {
368                 var list = db.Set<T>().AsExpandable().Where(selectWhere);
369                 Count = list.Count();
370                 if (isDESC)
371                     return list.OrderByDescending(orderBy).ToList();
372                 else
373                     return list.OrderBy(orderBy).ToList();
374             }
375             catch (Exception ex)
376             {
377                 Log_DG(ex.ToString());
378                 Count = 0;
379                 return default(List<T>);
380             }
381         }
382 
383         public static List<T> selectAllPaging<T, TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy, Boolean isDESC = false) where T : class
384         {
385             try
386             {
387                 var list = db.Set<T>().AsExpandable();
388                 if (isDESC)
389                     return list.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
390                 else
391                     return list.OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
392             }
393             catch (Exception ex)
394             {
395                 Log_DG(ex.ToString());
396                 return default(List<T>);
397             }
398         }
399         public static List<T> selectAllPaging<T, TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy, out int Count, Boolean isDESC = false) where T : class
400         {
401             try
402             {
403                 var list = db.Set<T>().AsExpandable();
404                 Count = list.Count();
405                 if (isDESC)
406                     return list.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
407                 else
408                     return list.OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
409             }
410             catch (Exception ex)
411             {
412                 Log_DG(ex.ToString());
413                 Count = 0;
414                 return default(List<T>);
415             }
416         }
417         public static List<T> selectAllPaging<T, TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy, Expression<Func<T, Boolean>> selectWhere, Boolean isDESC = false) where T : class
418         {
419             try
420             {
421                 var list = db.Set<T>().AsExpandable().Where(selectWhere);
422                 if (isDESC)
423                     return list.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
424                 else
425                     return list.OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
426             }
427             catch (Exception ex)
428             {
429                 Log_DG(ex.ToString());
430                 return default(List<T>);
431             }
432         }
433         public static List<T> selectAllPaging<T, TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy, Expression<Func<T, Boolean>> selectWhere, out int Count, Boolean isDESC = false) where T : class
434         {
435             try
436             {
437                 var list = db.Set<T>().AsExpandable().Where(selectWhere);
438                 Count = list.Count();
439                 if (isDESC)
440                     return list.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
441                 else
442                     return list.OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
443             }
444             catch (Exception ex)
445             {
446                 Log_DG(ex.ToString());
447                 Count = 0;
448                 return default(List<T>);
449             }
450         }
451 
452         #endregion
453     }
454 }

这里说明一下:

1、IEF_DBEntity_DG 帮助类的接口,当然我没有继承这个接口,这个接口只是我以后回顾的时候看的,并没有实际使用价值,只作为说明性的文字,不喜勿碰哈。

2、采用单例模式,这里不做过多说明,单例的介绍铺天盖地,我只是说,使用的时候,需要在这里改动两处对应到实体关系类上。

3、使用泛型,泛型在帮助类的重要性不必多说了吧,写帮助类不用泛型...啧啧啧。

4、Log_DG 这里直接封装了EF操作的错误信息,一般在try catch中调用,对错误进行日志的描述,便于后续的错误查找。

5、里面分别封装了 增加、删除、修改、查询四种基础的操作,并且每种操作都附有大量的重载(尤其是查询)便于适应更多不断变化项目;还有一些是快捷的操作,IsExist 这里直接返回数据是否存在。

6、所有的条件采用lambda表达式的方式,lambda表达式是比较新颖比较方便的条件判断条件筛选方式之一,在未来会更多地使用lambda表达式进行操作,在C#6.0已然是得到了很大的支持。

7、恰到适宜的out 输出参数,保证了在需要插入并且需要插入的结果需求的使用。

8、查询的分页支持,不必再写繁琐的分页,这里已经对分页进行了支持。

 

具体内容,参考类详情吧,后续更新修改,敬请期待! --柒小 2016年12月21日22:34:01

本文为七小站主原创作品,转载请注明出处:http://www.cnblogs.com/qixiaoyizhan/ 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

以上是关于ORM框架 EF - code first 的封装的主要内容,如果未能解决你的问题,请参考以下文章

ef code first 怎样指定哪些类生成数据表?那些不生成数据表?

Entity Framework学习-实体框架中的code-first迁移

实体框架-EF Code First Select外键

EF+Mysql+DDD框架搭建——code first准备

webapi框架搭建-数据访问ef code first

EF Code First 初试