2

我正在尝试使用 linq 在两个数据库之间同步表。我希望两个表中的主键(身份)相同。我无法使用 linq 完成此操作。

在搜索谷歌之后,我能得到的最接近的是:

Using DbContext as New DBContext()
    'Somewhere I read that the line below ensures queries run in the same session
    DbContext.Connection.Open() 

    Dim CopyOfShoe as New Shoe()
    CopyOfShoe.ID = OriginalShoe.ID
    CopyOfShoe.Color = OriginalShoe.Color

    DbContext.ExecuteCommand("SET IDENTITY_INSERT Shoes ON")
    DbContext.Shoes.InsertOnSubmit(CopyOfShoe)
    DbContext.SubmitChanges()
    DbContext.ExecuteCommand("SET IDENTITY_INSERT Shoes OFF")
End Using

但这会引发异常:

当 IDENTITY_INSERT 设置为 ON 或复制用户插入 NOT FOR REPLICATION 标识列时,必须为表“Shoes”中的标识列指定显式值。

我知道我可以通过使用 ExecuteCommand 插入带有现有身份的新记录来解决这个问题,但我想知道是否可以仅使用 linq。

4

0 回答 0