如何:检测和解决提交冲突 (LINQ to SQL)
LINQ to SQL 提供了许多资源,用于检测和解决因多个用户更改数据库而产生的冲突。 有关更多信息,请参见 如何:管理更改冲突 (LINQ to SQL)。
示例
下面的示例显示了捕获 ChangeConflictException 异常的 try/catch 块。 每个冲突的实体和成员信息会显示在控制台窗口中。
注意 |
---|
您必须将 using System.Reflection 指令(在 Visual Basic 中为 Imports System.Reflection)包含在内,以支持信息检索。有关更多信息,请参见 System.Reflection。 |
' Imports System.Reflection
Dim newCust As New Customer()
newCust.City = "Auburn"
newCust.CustomerID = "AUBUR"
newCust.CompanyName = "AubCo"
db.Customers.InsertOnSubmit(newCust)
Try
db.SubmitChanges(ConflictMode.ContinueOnConflict)
Catch e As ChangeConflictException
Console.WriteLine("Optimistic concurrency error.")
Console.WriteLine(e.Message)
Console.ReadLine()
For Each occ In db.ChangeConflicts
Dim metatable As MetaTable = db.Mapping.GetTable(occ.Object.GetType())
Dim entityInConflict = CType(occ.Object, Customer)
Console.WriteLine("Table name: {0}", metatable.TableName)
Console.Write("Customer ID: ")
Console.WriteLine(entityInConflict.CustomerID)
For Each mcc In occ.MemberConflicts
Dim currVal = mcc.CurrentValue
Dim origVal = mcc.OriginalValue
Dim databaseVal = mcc.DatabaseValue
Dim mi = mcc.Member
Console.WriteLine("Member: {0}", mi.Name)
Console.WriteLine("current value: {0}", currVal)
Console.WriteLine("original value: {0}", origVal)
Console.WriteLine("database value: {0}", databaseVal)
Next
Next
Catch ee As Exception
' Catch other exceptions.
Console.WriteLine(ee.Message)
Finally
Console.WriteLine("TryCatch block has finished.")
End Try
// using System.Reflection;
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
Customer newCust = new Customer();
newCust.City = "Auburn";
newCust.CustomerID = "AUBUR";
newCust.CompanyName = "AubCo";
db.Customers.InsertOnSubmit(newCust);
try
{
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException e)
{
Console.WriteLine("Optimistic concurrency error.");
Console.WriteLine(e.Message);
Console.ReadLine();
foreach (ObjectChangeConflict occ in db.ChangeConflicts)
{
MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType());
Customer entityInConflict = (Customer)occ.Object;
Console.WriteLine("Table name: {0}", metatable.TableName);
Console.Write("Customer ID: ");
Console.WriteLine(entityInConflict.CustomerID);
foreach (MemberChangeConflict mcc in occ.MemberConflicts)
{
object currVal = mcc.CurrentValue;
object origVal = mcc.OriginalValue;
object databaseVal = mcc.DatabaseValue;
MemberInfo mi = mcc.Member;
Console.WriteLine("Member: {0}", mi.Name);
Console.WriteLine("current value: {0}", currVal);
Console.WriteLine("original value: {0}", origVal);
Console.WriteLine("database value: {0}", databaseVal);
}
}
}
catch (Exception ee)
{
// Catch other exceptions.
Console.WriteLine(ee.Message);
}
finally
{
Console.WriteLine("TryCatch block has finished.");
}