Entity Framework generic usage

Source: Internet
Author: User

Because addition, deletion, modification, and query are common methods, it is impossible for us to complete addition, deletion, modification, and query in every data model. This method is too clumsy. We can write a parent class (including adding, deleting, modifying, and querying), and then let all data model classes inherit the parent class. Then, our parent class must be implemented using generics.

1 using System; 2 using System. collections. generic; 3 using System. data. entity. infrastructure; 4 using System. linq; 5 using System. linq. expressions; 6 using System. reflection; 7 using System. text; 8 using System. threading. tasks; 9 10 namespace ConsoleApplication1 11 {12 /// <summary> 13 /// define the generic type. It must be specified as a class, otherwise db. set <T> Returns 14 // </summary> 15 // <typeparam name = "T"> </typeparam> 16 class DALBase <T> where T: class 17 {18 // because we want to operate the database, first instantiate a context 19 Model1Container db = new Model1Container (); 20 21 # region add Method 22 /// <summary> 23 // Add Method 24 /// </summary> 25 /// <param name = "Model"> </param> 26 public void add (T Model) 27 {28 db. set <T> (). add (Model); 29 db. saveChanges (); 30} 31 # endregion 32 33 # region modify a single object 34 // <summary> 35 // modify a single object 36 /// </summary> 37 // <param name = "Model"> </param> 38 // <param name = "strs"> </param> 39 public void update (T Model, params string [] strs) 40 {41 DbEntityEntry entry = db. entry <T> (Model); 42 entry. state = System. data. entityState. unchanged; 43 foreach (string tempStr in strs) 44 {45 entry. property (tempStr ). isModified = true; 46} 47 db. saveChanges (); 48} 49 # endregion 50 51 # region batch modification, depending on reflection, slightly more complicated 52 /// <summary> 53 // batch modification based on reflection, slightly more complicated: 54 /// </summary> 55 /// <param name = "Model"> store the value in the attribute </param> 56 /// <param name = "where"> conditions for batch modification </param> 57 // <param name = "strs"> attributes </param> 58 public void updateBatch (T Model, expression <Func <T, bool> where, params string [] strs) 59 {60 // locate the 61 List that meets the conditions to be modified <T> tempList = db. set <T> (). where (where ). toList (); 62 // retrieve Type 63 Type t = typeof (T); 64 // obtain the public Attribute Set 65 List of T Type Using Reflection <PropertyInfo> tempPro = t. getProperties (System. reflection. bindingFlags. public | System. reflection. bindingFlags. instance ). toList (); 66 Dictionary <string, PropertyInfo> propertyDic = new Dictionary <string, PropertyInfo> (); 67 // traverses all attributes of T, save the modified content to the dictionary 68 tempPro. forEach (p => {if (strs. contains (p. name) {propertyDic. add (p. name, p) ;}}); 69 // traverse the attributes to be modified 70 foreach (string str in strs) 71 {72 if (propertyDic. containsKey (str) 73 {74 PropertyInfo propertyInfo = propertyDic [str]; 75 // get the value of the property to be modified 76 object value = propertyInfo. getValue (Model, null); 77 foreach (T tempData in tempList) 78 {79 // set the value to 80 propertyInfo. setValue (tempData, value, null ); 81} 82} 83} 84} 85 # endregion 86 87 # region Delete Object id 88 // <summary> 89 // Delete Object id 90 /// </summary> 91 // <param name = "Model"> </param> 92 public void remove (T Model) 93 {94 db. set <T> (). attach (Model); 95 db. set <T> (). remove (Model); 96 db. saveChanges (); 97} 98 # endregion 99 100 # Delete region according to the condition 101 // <summary> 102 // delete operation 103 // </summary> 104 /// <param name = "remWhere"> </param> 105 public void removeByWhere (Expression <Func <T, bool> remWhere) 106 {107 List <T> tempList = db. set <T> (). where (remWhere ). toList (); 108 tempList. forEach (t => {db. set <T> (). attach (t); db. set <T> (). remove (t);}); 109 db. saveChanges (); 110} 111 # endregion112 113 # region generally has a conditional query of 114 // <summary> 115 // generally, the conditional query is 116 /// </summary> 117 // <param name = "where"> </param> 118 // <returns> </returns> 119 public List <T> getList (System. linq. expressions. expression <Func <T, bool> where) 120 {121 return db. set <T> (). where (where ). toList (); 122} 123 # endregion124 125 # region with conditional sorting, page size query 126 /// <summary> 127 // with conditional sorting, page number page size query 128 /// </summary> 129 /// <typeparam name = "TKey"> </typeparam> 130 /// <param name = "where"> </param> 131 // <param name = "orderBy"> </param> 132 // <param name = "pageSize"> </param> 133 /// <param name = "pageIndex"> </param> 134 // <returns> </returns> 135 public List <T> getListOrder <TKey> (Expression <Func <T, bool> where, Expression <Func <T, TKey> orderBy, int pageSize, int pageIndex) 136 {137 return db. set <T> (). where (where ). orderBy (orderBy ). skip (pageIndex-1 ). take (pageSize ). toList (); 138} 139 # endregion140} 141}View Code

Reflection is used in it, which may be a bit complicated. EF is about to come to an end. Next we will record the learning process of mvc. A small project may be written in the future, using mvc + EF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.