【发布时间】:2009-01-22 20:06:30
【问题描述】:
我是第一次使用 LINQ,我遇到了一些我对 DataContext 不完全理解的行为。希望 StackOverflow 可以提供帮助。
基本上,似乎一旦我的 DataContext 遇到异常,它要么缓存该异常,要么永远不会完全恢复。在我的具体情况下,一旦我尝试将一个太大的字符串传递给我的数据库,它会为所有后续字符串抛出相同的异常。
我有一张这样的桌子:
DisplayString(
StringID nvarchar(255)
,CultureCode varchar(25)
,DisplayString nvarchar(255)
)
在 .Net 中,我创建了一个 DataContext,我使用 LINQ to SQL 类将其映射到该表。
Dim context As New LinqTableMappingDataContext(
My.Settings.LocalizationStringsConnectionString)
然后我创建一堆测试字符串,遍历每个字符串并将它们发送到我的表。
Dim arr As String() =
{"aaaaa", "adsfs", "wefwf", "dfgsfg", "ergsdfg",
"fsdgergd", "Sdgdfgegd", "ergdfgsfd"}
For Each a As String In arr
addToLinq(a)
Next
这很好用。但是,如果我在索引 1 处添加以下字符串,所有后续插入都会失败,抛出与长字符串相同的异常 (SqlException)。
"WARNING: This computer program is protected by copyright law and international
treaties. Unauthorized reproduction of this program, or any portion of it, may
result in severe civil and criminal penalties, and will be prosecuted to the
maximum extent possible under the law."
这是我的 AddToLinq() 方法。
Private Sub AddToLinq(ByVal stringID As String)
Dim f As New DisplayString
Try
Dim count As Integer = (From str In context.DisplayStrings _
Where str.StringID = stringID Select str).Count
If count = 0 Then
f.StringID = stringID
f.CultureCode = "en-US"
f.DisplayString = stringID
context.DisplayStrings.InsertOnSubmit(f)
context.SubmitChanges()
Console.WriteLine("SUBMITTED: " & stringID)
End If
Catch ex1 As SqlException
Console.WriteLine("------------------------------------------------")
Console.WriteLine("EXCEPTION: " & ex1.Message)
Console.WriteLine(stringID)
Console.WriteLine(stringID.Length)
Console.WriteLine("------------------------------------------------")
Catch ex As DuplicateKeyException
Console.WriteLine(ex.Message)
End Try
End Sub
如果有人可以帮助我,那就太好了,谢谢。
【问题讨论】: