Reputation: 5526
I am playing with ASP.NET MVC3 Beta 2 and am using Linq to SQL for the Model. I one of my controllers, I have an action like so:
UserDataContext db = new UserDataContext();
[HttpPost]
public ViewResult Edit(User um) {
if (!TryUpdateModel(um)) {
ViewBag.UpdateError = "Update Failure";
return View("Details", um);
}
//How do I update the existing user? The following fails
//db.Users.Attach(um, true);
db.SubmitChanges();
return View("Details", um);
}
The User object has fields for Id, FirstName, LastName etc. Is there a way update the existing object (matching by id) without first selecting it, then manually reassigning all the fields?
Upvotes: 0
Views: 2197
Reputation: 9318
you can do something like
var user = new User
{
id = um.Id,
}
db.Users.Attach(um, user);
db.SubmitChanges();
Upvotes: 0
Reputation: 2106
A different way to tackle the problem is as follows. Don't let the MVC framework create a new User object for you, load the User you need from the DataContext and update that object using the ValueCollection.
UserDataContext db = new UserDataContext();
[HttpPost]
public ViewResult Edit(int userID, FormCollection collection)
{
var user = db.Users.SingleOrDefault(o => o.ID == userID);
// make sure user or collection isn't null.
if (!TryUpdateModel(user, collection))
{
ViewBag.UpdateError = "Update Failure";
return View("Details", um);
}
db.SubmitChanges();
return View("Details", um);
}
Upvotes: 1
Reputation: 4197
yeah u can use datacontext.executecommand or datacontext.executequery where u can write sql query and u can update any table row without pulling it inmemory,actually linq to sql works with in memory objects mean if u want to perform any operation first u need to fetch it then only u can perform the operatin,exexutecommand and executequery is the ony way to do it
Upvotes: 2