Reputation: 18109
I am trying to update a record in my database using Linq to Sql. I'd like to update all fields, which will come from a new object, however if I try this:
originalObject = newObject
db.submitChanges()
It doesn't save the changes because it thinks the primary key has been changed (Or something along those lines.. it gives no error but doesn't update the object in the database)
I tried overwriting it like:
Dim originalKey = originalObject.MyPrimaryKey
originalObject = newObject
originalObject.MyPrimaryKey = originalKey
db.SubmitChanges()
...but that doesn't work either. If I set individual properties they will be saved (ie: originalObject.PropertyName = "New Value") then submitChanges, it works, but the object has about a hundred properties which I don't want to have to update each one individually. So, how can I update the object and submitChanges() successfully?
Upvotes: 1
Views: 1481
Reputation: 5462
The goal of the code below is to update an entity on the database without having to map the fields from the detached object to the attached one (in the database).
var dtCxt = Util.GetDtCxt();
dtCxt.YourTable.Attach(detachedObject, GetObjectById(detachedObject.id));
dtCxt.SubmitChanges();
GetObjectById uses another DataContext. You must do this.
private Incoterm GetObjectById(int id)
{
var dtCxt = Util.GetDtCxt();
return dtCxt.YourTable.FirstOrDefault(i => i.id == id);
}
Upvotes: 0
Reputation: 13940
If you already have the modified entity object, you should be able to use (yourDataContext).(yourTable).Attach(modifiedObject, true), followed by SubmitChanges.
Upvotes: 1