当前位置: 当前位置:首页 >人工智能 >LINQ to SQL实现数据访问通用基类正文

LINQ to SQL实现数据访问通用基类

作者:域名 来源:IT科技 浏览: 【】 发布时间:2025-11-05 14:04:17 评论数:

view plaincopy to clipboardprint?现数

1.        

LINQ to SQL实现数据访问通用基类

2.       public void Save(Customer toSave)  

3.       {  

4.       //the old data context is no more, we need to create a new one  

5.       DataClassesDataContext context = new DataClassesDataContext();  

6.       //serialize and deserialize the entity to detach it from the  

7.       //old data context. This is not part of .NET, I am calling  

8.       //my own code here  

9.       toSave = EntityDetacher.Detach(toSave);  

10.   //is the entity new or just updated?  

11.   //ID is the customer tables identity column, so new entities should  

12.   //have an ID == 0  

13.   if (toSave.ID == 0)  

14.   {  

15.   //insert entity into Customers table  

16.   context.Customers.InsertOnSubmit(toSave);  

17.  }  

18.   else 

19.   {  

20.   //attach entity to Customers table and mark it as "changed"  

21.   context.Customers.Attach(toSave, true);  

22.  }  

23.   //attach or save all "bill" child entities  

24.   foreach (Bill bill in toSave.Bills)  

25.   {  

26.   if (bill.ID == 0)  

27.   {  

28.   context.Bills.InsertOnSubmit(bill);  

29.  }  

30.   else 

31.    

32.   {  

33.   context.Bills.Attach(bill, true);  

34.  }  

35.   //attach or save all "BillingItem" child entities  

36.   foreach (BillingItem billingitem in bill.BillingItems)  

37.   {  

38.   if (bill.ID == 0)  

39.   {  

40.   context.BillingItems.InsertOnSubmit(billingitem);  

41.  }  

42.   else 

43.   {  

44.   context.BillingItems.Attach(billingitem, true);  

45.  }  

46.   }  

47.   }  

48.   }