document 表為例 寫入靜態類 NorthwindDataProvider:
Controller可直接調用:如
1 //獲取document表全部數據 2 NorthwindDataProvider.GetDocuments()
document 類:EF 映射
1 public static class NorthwindDataProvider 2 { 3 const string NorthwindDataContextKey = "DXNorthwindDataContext"; 4 5 public static NWindEntities DB 6 { 7 get 8 { 9 if (HttpContext.Current.Items[NorthwindDataContextKey] == null) 10 HttpContext.Current.Items[NorthwindDataContextKey] = new NWindEntities(); 11 return (NWindEntities)HttpContext.Current.Items[NorthwindDataContextKey]; 12 } 13 } 14 /// <summary> 15 /// 查詢所有document表數據 16 /// </summary> 17 /// <returns></returns> 18 public static IEnumerable GetDocuments() 19 { 20 return from document in DB.Documents select document; 21 } 22 /// <summary> 23 /// 增加一條document數據 24 /// </summary> 25 /// <param name="doc">傳入新數據</param> 26 public static void AddDocument(Document doc) 27 { 28 DB.Documents.AddObject(doc); 29 DB.SaveChanges(); 30 } 31 /// <summary> 32 /// 根據ID查詢document數據 33 /// </summary> 34 /// <param name="id">傳入主鍵</param> 35 /// <returns></returns> 36 public static Document GetDocumentById(int id) 37 { 38 var val = from document in DB.Documents where document.DocumentId == id select document; 39 return val.First(); 40 } 41 /// <summary> 42 /// 修改一條document數據 43 /// </summary> 44 /// <param name="doc">傳入修改後的數據</param> 45 public static void UpdateDocument(Document doc) 46 { 47 Document oldDoc = DB.Documents.First(p => p.DocumentId == doc.DocumentId); 48 oldDoc.DocumentCode = doc.DocumentCode == null ? oldDoc.DocumentCode : doc.DocumentCode; 49 oldDoc.DocumentName = doc.DocumentName == null ? oldDoc.DocumentName : doc.DocumentName; 50 oldDoc.DocumentMemo = doc.DocumentMemo == null ? oldDoc.DocumentMemo : doc.DocumentMemo; 51 oldDoc.DocumentType = doc.DocumentType == null ? oldDoc.DocumentType : doc.DocumentType; 52 oldDoc.DocumentDate = doc.DocumentDate == null ? oldDoc.DocumentDate : doc.DocumentDate; 53 DB.SaveChanges(); 54 } 55 /// <summary> 56 /// 刪除一條document數據 57 /// </summary> 58 /// <param name="id">被刪除數據的主鍵</param> 59 public static void deleteDocument(int id) 60 { 61 var obj = DB.Documents.Where(c => c.DocumentId == id).First(); 62 DB.DeleteObject(obj); 63 DB.SaveChanges(); 64 } 65 }