Skip to main content
 首页 » 编程设计

c#之使用 LINQ SQL 查看更新是否成功

2024年02月20日16me-sa

我从教程中找到这段代码:

Product bev1 = beverages.ElementAtOrDefault(10); 
if (bev1 != null) 
{ 
    Console.WriteLine("The price of {0} is {1}. Update to 20.0",  
                      bev1.ProductName, bev1.UnitPrice); 
    bev1.UnitPrice = (decimal)20.0; 
} 
// submit the change to database 
db.SubmitChanges(); 

我们如何知道更新是否成功?

请您参考如下方法:

一种方法知道的是没有抛出异常。

第二种方法确保使用 GetChangeSet获取数据上下文跟踪的修改对象的方法。

示例表单 msdn

Northwnd db = new Northwnd(@"c:\northwnd.mdf"); 
 
var custQuery = 
    from cust in db.Customers 
    where cust.City == "London"  
    select cust; 
 
foreach (Customer custObj in custQuery) 
{ 
    Console.WriteLine("CustomerID: {0}", custObj.CustomerID); 
    Console.WriteLine("\tOriginal value: {0}", custObj.City); 
    custObj.City = "Paris"; 
    Console.WriteLine("\tUpdated value: {0}", custObj.City); 
} 
 
//get object modified  
ChangeSet cs = db.GetChangeSet(); 
Console.Write("Total changes: {0}", cs); 
// Freeze the console window. 
Console.ReadLine(); 
 
db.SubmitChanges();