LINQ to SQL A member defining the identity of the object cannot be changed
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.
精彩评论