开发者

How to properly update a model entity instance in EF?

I have some code like belows. This works but I think it's not clear enough and requires me to write lengthy code (assigning each property manually).

// POST: /TableA/Edit
[HttpPost]
public ActionResult Edit(TableA formdata)
{
    TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id);

    //A foreign key model in another TableB
    var tbb = myDB.TableB.First(a => a.Id == formdata.TableB.Id);
    temp.TableB = tbb;

    //fields in this table
    temp.field1= formdata.field1;
    temp.field2= formdata.field2;
    temp.field3开发者_运维知识库= formdata.field3;

    myDB.SaveChanges();
    return RedirectToAction("Index");
}

Can I have some code similar to object initializers:

    TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id)
    {
        TableB =  myDB.TableB.First(a => a.Id == formdata.TableB.Id),
        field1= formdata.field1,
        field2= formdata.field2,
        field3= formdata.field3,
    }

    myDB.SaveChanges();
    return RedirectToAction("Index");


Using i.e. AutoMapper you could write it like this (possibly have to set up to limit the mapping between the objects to the properties you want copied):

[HttpPost]
public ActionResult Edit(TableA formdata)
{
    TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id);
    temp.TableB = myDB.TableB.First(a => a.Id == formdata.TableB.Id);

    AutoMapper.Mapper.Map(formdata, temp);
    myDB.SaveChanges();
    return RedirectToAction("Index");
}


You could use the TryUpdateModel method

Updates the specified model instance using values from the controller's current value provider and included properties.

[HttpPost]
public ActionResult Edit(TableA formdata)
{
    if (ModelState.IsValid)
    {
        TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id);
        if (TryUpdateModel<TableA>(temp))
        {
            myDB.SaveChanges();
            return RedirectToAction("Index");
        }
    }

    return View();
}

You would be better off calling Controller.TryUpdateModel Method (TModel, String[]) to prevent properties you don't want to be editable from being added to the form before it's posted. This includes ID's or other fields you don't want the form to post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜