2

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();
}
Coomanperson
  • 132
  • 2
  • 11

1 Answers1

5

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.

Nilesh
  • 2,583
  • 5
  • 21
  • 34
  • This is what i have been trying to get to work, however it submits the form, as in the code went through ok, but nothing is added to the Database. I have confirmed that RecFoo does indeed have an id, not sure what the issue is. – Coomanperson Aug 23 '13 at 17:02
  • You need to set the EntityState to modified before saving changes. – Nilesh Aug 23 '13 at 17:04
  • Check [this](http://stackoverflow.com/questions/386211/linq-to-sql-submitchanges-not-updating-fields-why) post and may be [this](http://geekswithblogs.net/michelotti/archive/2007/12/25/117984.aspx) as well – Nilesh Aug 23 '13 at 17:19
  • This worked, however in order for the context to realize that the object was indeed changed, i had to refresh it, I will accept this as answer, and post the line of code that made it work for me in the edit, much appreciated everyone. – Coomanperson Aug 23 '13 at 17:33