开发者

Linq to SQL - Update object without selecting it first

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 开发者_StackOverflow中文版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?


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


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); 
}


you can do something like

var user = new User
{
    id = um.Id,
}
db.Users.Attach(um, user);
db.SubmitChanges();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜