会员登录 - 用户注册 - 设为首页 - 加入收藏 - 网站地图 LINQ to SQL实现数据访问通用基类!

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

时间:2025-11-04 23:10:36 来源:益强数据堂 作者:数据库 阅读:649次

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.   } 

(责任编辑:IT科技类资讯)

推荐内容
  • 网吧电脑脱离主机教程(轻松拆解,自由组装,享受自由游戏体验)
  • 智能建筑中最常见的物联网设备连接选项
  • 亚马逊向开发者开放物联网计划
  • eSIM技术如何简化全球BVLOS无人机操作?
  • 石材电脑锯开料机使用教程(学习如何正确使用石材电脑锯开料机)
  • 边缘计算引入企业物联网解决方案的优势