Reputation: 134
So if want to update a row in the db using the values in a received object with the same PK, how would we do that. The reason this is needed is because the objects are quite extensive and this would I create another place where we have to change field names if we update the database. So my question is how does one go about assigning an object to an object retrieved from the database using LINQ? I will show what i'm talking about to clarify.
//Foo Object Received up here, called RecFoo
using (var newContext = new FooDataContext())
{
var obj = newContext.T_Foo.Single(x=>x.Id == RecFoo.id);
//Set obj = recFoo (Directly)
newContext.SubmitChanges();
}
I know we can set each individual attribute (obj.Name = RecFoo.Name...), but is there any way that we can just take the received object using the PK id and assign it all the values that are inside of RecFoo?
EDIT: Solution
using (var newContext = new FooDataContext())
{
//var obj = newContext.T_Foo.Single(x=>x.Id == RecFoo.id);
//Set obj = recFoo (Directly)
newContext.T_Foo.Attach(recFoo);
newContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, recFoo);
newContext.SubmitChanges();
}
Upvotes: 2
Views: 572
Reputation: 2691
Have you tried newContext.YourEntity.Attach(YourAlreadyPopulatedObject)
In this you just tell Linqtosql that the record already exists in the database and you are updating it.
Upvotes: 5