Welcome

首页 / 软件开发 / LINQ / Linq to SQL之更新

Linq to SQL之更新2011-08-04 博客园 紫色阴影本文接着上篇Linq to SQL之查询和添加,还是以Northwind数据库为例,介绍使用Linq to SQL怎样对 数据库的数据进行更新及冲突的相关问题。

首先对Customers表的一条记录进行更新:

NorthwindDataContext ctx = new NorthwindDataContext();
Customer alfki = ctx.Customers.Single(c => c.CustomerID == "ALFKI");
Console.WriteLine("Before update, the company name of Alfki is: " + alfki.CompanyName);
alfki.CompanyName = "New Company Name";
ctx.SubmitChanges();
Customer newAlfki = ctx.Customers.Single(c => c.CustomerID == "ALFKI");
Console.WriteLine("After update, the company name of Alfki is: " + alfki.CompanyName);

通过屏幕输出,可以看到数据的确已经更新成功了

Before update, the company name of Alfki is: Alfreds Futterkiste

After update, the company name of Alfki is: New Company Name

现在,把调用SubmitChanges方法放在最后,看看会发生什么:

NorthwindDataContext ctx = new NorthwindDataContext();
Customer alfki = ctx.Customers.Single(c => c.CustomerID == "ALFKI");
Console.WriteLine("Before update, the company name of Alfki is: " + alfki.CompanyName);
alfki.CompanyName = "New Company Name";

Customer newAlfki = ctx.Customers.Single(c => c.CustomerID == "ALFKI");
Console.WriteLine("Before submit changes, the company name of Alfki is: " + alfki.CompanyName);

ctx.SubmitChanges();

屏幕的输出为:

Before update, the company name of Alfki is: Alfreds Futterkiste

Before submit changes, the company name of Alfki is: New Company Name

可以看到,第二次查询是在更新提交之前,这时候数据库中的值还没有改变,按理说这时候去进行数 据库查询得到的值应该还是旧值,但是代码运行后发现查询出来的值确是更新后的值。这是为什么呢?其 实原因还是上篇提到过的Identity Cache,DataContext以主键为key对数据对象进行缓存以此对数据对象 的生命周期进行跟踪。借助Sql profile可以发现,第二次调用ctx.Customers.Single时,数据库并没有 查询的记录,这里DataContext直接在内存中查找该对象并且返回。当然也可以关闭这种机制,只需要调 用ctx.ObjectTrackingEnabled = false。DataContext就不再对数据对象进行Identity Cache,每次查询 结果都是通过查询数据库得到。

数据库数据更新通常会遇到同步冲突的问题,比如获得数据以后,对数据进行一系列的操作,然后把 新的数据更新回数据库。如果在数据进行操作的同时,有其它程序或者管理员改动了该数据的值,这样就 会发生冲突。到底数据是应该保留现有的值呢还是把改动的值强行更新到数据库呢?Linq to SQL提供了 很多方法来解决这种冲突问题。