讲解ASP.NET中LINQ to SQL 实现数据访问通用基类(2)
用断开模式的LINQ to SQL实现数据访问层
所以,在断开的LINQ模式下,我们如何实现数据层的Save( )方法?
我们必须
- Detach the entity from the old data context从旧的数据上下文中分离实体
- Create a new data context创建一个新的数据上下文
- Attach the entity to the new context附加实体到新的数据上下文
- Submit changes提交更改
在源代码,它看起来像这样:
view plaincopy to clipboardprint?
1.
2. public Customer Load(int CustomerID)
3. {
4. DataClassesDataContext context = new DataClassesDataContext();
5. return context.Customers.Single(c => c.ID == CustomerID);
6. }
7.
8. public void Save(Customer toSave)
9. {
10. //the old data context is no more, we need to create a new one
11. DataClassesDataContext context = new DataClassesDataContext();
12. //serialize and deserialize the entity to detach it from the
13. //old data context. This is not part of .NET, I am calling
14. //my own code here
15. toSave = EntityDetacher<Customer>.Detach(toSave);
16. //is the entity new or just updated?
17. //ID is the customer table's identity column, so new entities should
18. //have an ID == 0
19. if (toSave.ID == 0)
20. {
21. //insert entity into Customers table
22. context.Customers.InsertOnSubmit(toSave);
23. }
24. else
25. {
26. //attach entity to Customers table and mark it as "changed"
27. context.Customers.Attach(toSave, true);
28. }
29. }
现在只要你喜欢,您可以加载修改任意多实体,并且只提交他们一部分到数据库。但由于使用断开的LINQ ,这个程序并不会感知到LINQ实体之间的关系。
例如,假设在业务层或用户界面层您要做到以下几点:
view plaincopy to clipboardprint?
1.
2. //load currently selected customer from database
3. Customer customer = new CustomersRepository().Load(1);
4. //change the customer's first name
5. customer.FirstName = "Homer";
6. //add a new bill with two billingitems to the customer
7. Bill newbill = new Bill
8. {
9. Date = DateTime.Now,
10. BillingItems =
11. {
12. new BillingItem(){ItemPrice=10, NumItems=2},
13. new BillingItem(){ItemPrice=15, NumItems=1}
14. }
15. };
16. customer.Bills.Add(newbill);
17. //create a new provider to simulate new ASP.NET page request
18. //save the customer
19. new CustomersRepository().Save(customer);
这个断开模式下,上述Save( )方法将提交变更到FirstName列,但是忽略了new bill和billing items。为了做到这一点,我们还需要附加或插入递归所有相关的子实体(child entities):
view plaincopy to clipboardprint?
1.
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 table's identity column, so new entities should
12. //have an ID == 0
13. if (toSave.ID == 0)
14. {
15.<