Ef curd operation, efcurd operation
Ef curd operations
The database Northwind,: https://northwinddatabase.codeplex.com/
Add
1 /// <summary> 2 /// Add 3 /// </summary> 4 /// <returns> </returns> 5 public static int Add () 6 {7 using (var db = new NorthwindEntities () 8 {9 var customer = new MERs () 10 {11 CustomerID = "fanguza", 12 Address = "Earth ", 13 City = "Guangdong", 14 Phone = "13800138000", 15 CompanyName = "", 16 ContactName = "" 17 }; 18 19 // Method 20 // db. MERs. add (customer); 21 22 // method 2 23 var entry = db. entry (customer); 24 entry. state = EntityState. added; 25 26 return db. saveChanges (); 27} 28}
Delete
1 /// <summary> 2 /// Delete 3 /// </summary> 4 /// <returns> </returns> 5 static int Delete () 6 {7 using (var db = new NorthwindEntities () 8 {9 var customer = new MERs () 10 {11 CustomerID = "fanguzi" 12}; 13 14 db. MERs. attach (customer); 15 db. MERs. remove (customer); 16 17 return db. saveChanges (); 18} 19}
Change
1 /// <summary> 2 /// Edit (modify) 3 /// </summary> 4 /// <returns> </returns> 5 static int Edit () 6 {7 using (var db = new NorthwindEntities () 8 {9 var customer = db. MERs. firstOrDefault (u => u. customerID = "fanguzai"); 10 11 if (customer = null) 12 {13 return 0; 14} 15 16 customer. contactName = "erwuzai"; 17 return db. saveChanges (); 18} 19}
Query
1 /// <summary> 2 /// Query 3 /// </summary> 4 static MERs Query () 5 {6 using (var db = new NorthwindEntities ()) 7 {8 var query = 9 db. MERs. where (u => u. contactName = "fanguza "). orderBy (u => u. contactName ). take (1); 10 11 return query. firstOrDefault (); 12} 13}
Paging
1 public IQueryable <Customers> GetPageOfCustomerses <TKey> (int pageIndex, int pageSize, 2 Expression <Func <Customers, bool> wherExpression, 3 Expression <Func <Customers, TKey> orderByExpression) 4 {5 using (var db = new NorthwindEntities () 6 {7 // sort 8 return db before paging. MERs. where (wherExpression ). orderBy (orderByExpression ). skip (pageIndex-1) * pageSize ). take (pageSize); 9} 10}
Batch increase
1 static void BatchAdd () 2 {3 using (var db = new NorthwindEntities () 4 {5 for (var I = 0; I <50; I ++) 6 {7 var customer = new MERs () 8 {9 CustomerID = "fanguzai" + I, 10 Address = "China", 11 City = "Guangzhou ", 12 Phone = "13800138000" + I, 13 CompanyName = "Yangchun No. 1", 14 ContactName = "anti-bone" + i15}; 16 17 db. MERs. add (customer); 18} 19 20 db. saveChanges (); 21} 22}
Others
1 public IQueryable<Customers> GetCustomerses<TKey>(Expression<Func<Customers, bool>> whereExpression,2 Expression<Func<Customers, TKey>> orderExpression)3 {4 using (var db = new NorthwindEntities())5 {6 return db.Customers.Where(whereExpression).OrderBy(orderExpression);7 }8 }