Tarik
Tarik

Reputation: 81721

How to update entire Object in Linq2SQL

Lets suppose I have a method like that in MVC

public void UpdateUser(User user)
{
  DataContext db = new DataContext();
  User u = db.Users.First(t=>t.UserId = user.UserId);
  u.Name = user.Name;
  u.LastName = user.LastName;
  db.SubmitChanges();
}

If we start thinking that we have properties more than Name and LastName, this process is getting cumbersome and I wonder whether there is way to easily reconcile these two objects and update it quickly.

Maybe something like this:

public void UpdateUser(User user)
{
  DataContext db = new DataContext();
  User u = db.Users.First(t=>t.UserId = user.UserId);
  u.MergeWith(user);
  db.SubmitChanges();
}

I think that would much easier.

Upvotes: 2

Views: 124

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

using(var db = new DataContext()) {
    db.Users.Attach(user, true);
    db.SubmitChanges();
}

the true says "this object has changes, and needs to be committed".

The only downside of this is that it now doesn't know which values have changed, so will try to update them all. There is also an Attach that takes the old and new, but the old shouldn't be from the data-context you are talking to.

Upvotes: 2

Related Questions