views:

1148

answers:

2

Hi,

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 DemoDataContext()

    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.

+2  A: 

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
Mark Byers
It gave the error like this :Row not found or changed. </br>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. </br>Exception Details: System.Data.Linq.ChangeConflictException: Row not found or changed.
Angkor Wat
A: 

Hi,

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.

Angkor Wat