开发者

LINQ to SQL A member defining the identity of the object cannot be changed

开发者 https://www.devze.com 2022-12-12 23:33 出处:网络
I\'m writing a Generic for LINQ to SQL CUD. I \'Generic Insert Public Shared Sub Add(Of T As Class)(ByVal entity As T)

I'm writing a Generic for LINQ to SQL CUD. I

'Generic Insert

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

The genric Insert is working good.

'Generic Update

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

    Dim db As New DemoD开发者_StackOverflow社区ataContext()

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

End Sub

'Use Generic Update

    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)

Error message from Generic Update.

Value of member 'Id' of an object of type 'TestAuthor' changed. A member defining the identity of the object cannot be changed. Consider adding a new object with new identity and deleting the existing one instead.

What do I need to modify the Generic Update? Thank you.


Your newEntity object doesn't have Id 4, it has Id 0, so the two objects aren't considered to correspond to the same database row.

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


FYI, LINQ to SQL assumes that the object you are attaching is un-modified. I read a post here, which has a good solution without adding TimeStamp column.

'Generic Update 'Need to Imports System.Data.Linq

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.Refresh(RefreshMode.KeepCurrentValues, newEntity)

db.SubmitChanges()

End Sub

'Use Generic Update

    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)

Thank you.

0

精彩评论

暂无评论...
验证码 换一张
取 消