LINQ to SQL无法更改定义对象标识的成员

时间:2009-11-29 10:00:28

标签: vb.net linq-to-sql

我正在为LINQ to SQL CUD编写Generic。我

'通用插入

Public Shared Sub Add(Of T As Class)(ByVal entity As T)

    Using db As New APIUDataContext()

        db.GetTable(Of T)().InsertOnSubmit(entity)
        db.SubmitChanges()

    End Using

genric Insert工作正常。

'通用更新

Public Shared Sub Update(Of T As Class)(ByVal oldEntity As T, ByVal newEntity As T)

    Dim db As New DemoDataContext()

    db.GetTable(Of T)().Attach(newEntity, oldEntity)
    db.SubmitChanges()

End Sub

'使用通用更新

    Dim oldEntity As New TestAuthor
    oldEntity.Id = 4
    oldEntity.FirstName = "James"

    Dim newEntity As New TestAuthor
    newEntity.FirstName = TextBox1.Text
    newEntity.LastName = TextBox2.Text

    GenericCUD.Update(oldEntity, newEntity)

来自通用更新的错误消息。

“TestAuthor”类型的对象的成员“Id”的值已更改。 无法更改定义对象标识的成员。 考虑添加具有新标识的新对象并删除现有标识。

修改通用更新需要什么?谢谢。

2 个答案:

答案 0 :(得分:4)

你的newEntity对象没有Id 4,它有Id 0,所以这两个对象不被认为对应于同一个数据库行。

Dim newEntity As New TestAuthor
newEntity.Id = oldEntity.Id
newEntity.FirstName = TextBox1.Text
newEntity.LastName = TextBox2.Text

答案 1 :(得分:2)

仅供参考,LINQ to SQL假定您要附加的对象未经修改。我读了一篇帖子here,它有一个很好的解决方案,但没有添加TimeStamp列。

'通用更新 '需要导入System.Data.Linq

公共共享子更新(T作为类)(ByVal oldEntity为T,ByVal newEntity为T)

Dim db As New DemoDataContext()

db.GetTable(Of T)().Attach(newEntity, oldEntity)
db.Refresh(RefreshMode.KeepCurrentValues, newEntity)

db.SubmitChanges()

End Sub

'使用通用更新

    Dim oldEntity As New TestAuthor
    oldEntity.Id = 4

    Dim newEntity As New TestAuthor
    newEntity.Id = oldEntity.Id
    newEntity.FirstName = TextBox1.Text
    newEntity.LastName = TextBox2.Text

    GenericCUD.UpdateMe(oldEntity, newEntity)

谢谢。