【问题标题】:Auto-increment a primary key in the LINQ to SQL DataContext "Insert" partial method在 LINQ to SQL DataContext“插入”部分方法中自动增加主键
【发布时间】:2010-09-21 11:21:36
【问题描述】:

我想做的是以下。我有一个表 Products,其中包含一个私钥 ProductID。我不想在插入时让 SQL Server 自动增加 P​​roductID,而是想在 DataContext 部分方法“InsertProduct”中增加它:

Partial Public Class MyDataContext

    Private Sub InsertProduct(ByVal instance As Product)

        Dim id As Integer = Me.Products.Max(Function(p As Product) p.ProductID) + 1
        instance.ProductID = id

        Me.ExecuteDynamicInsert(instance)

    End Sub

End Class

但是,这仅在插入第一个 Product 实例时才有效。尝试插入第二个实例时,检索到的 id 与第一个相同,

Using context As New MyDataContext

    Dim product1 As New Product
    context.Products.InsertOnSubmit(product1)
    context.SubmitChanges() 'This works

    Dim product2 As New Product
    context.Products.InsertOnSubmit(product2)
    context.SubmitChanges() 'DuplicateKeyException

End Using

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

    标签: linq-to-sql


    【解决方案1】:

    InsertProduct 没有在上面的代码中声明为分部方法。这是您帖子中的拼写错误,还是您声明它的签名与要求的签名不同,因此它没有被执行?

    [编辑] 我不是 VB 程序员(我使用 C#),但我认为您的代码需要将代码声明为部分代码以及在设计器中。无论如何,这在 C# 中是正确的。

    【讨论】:

      【解决方案2】:

      InsertProduct 在设计器生成的文件 (MyDataClasses.designer.vb) 中被声明为部分方法。

      它被执行了,实际上我可以在 InsertProduct 中插入一个断点并观察 product1 的一切正常运行。对于 product2,context.SubmitChanges() 抛出异常,但没有命中断点。

      【讨论】:

        【解决方案3】:

        我真的建议让 SQL Server 进行增量编号。上述方法即使您确实可以正常工作,但在多用户场景中加载时也会失败,在这种情况下,他们都获得相同的 ID 并尝试插入相同的 ID。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多