开发者

How to Manually Updating Model in Entity Framework

I am new to .NET MVC (Learning). I have the following method in Controller(this is not clean code and I am learning)

        [HttpPost]
        public ActionResult Edit(ProductCategoryLocation viewModel)
        {
            if (ModelState.IsValid)
            {
                var product = viewModel.Product;
                product.Category = db.Categories
                    .Where(c => c.ID == viewModel.CategoryID).Single();                                 
                db.Entry(product).State = EntityState.Modified;               
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(viewModel);
        }

The View Model Has Product, Location and Category Types and CategoryID and LocationID. In the POST method I am getting the category ID from the View Model, Update the Category of the Product and then Update the Model to the Database. Any changes to the properties of Products gets saved except the manually changed Category.

Is there a mistake / Am I missing something? Is this the right开发者_StackOverflow way of doing update using View Model?


You can directly assign CategoryID of the view model to CategoryID of the product. This way you do not have to retrieve the category from the database.

    [HttpPost]
    public ActionResult Edit(ProductCategoryLocation viewModel)
    {
        if (ModelState.IsValid)
        {
            var product = viewModel.Product;
            product.CategoryID = viewModel.CategoryID;                                
            db.Entry(product).State = EntityState.Modified;               
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(viewModel);
    }

If you do not have a scalar property CatagoryID you have to define it in the Product class

public class Product
{
   public int ID { get; set; }

   //other properties

   public int CategoryID { get; set; }
   public virtual Category Category { get; set; }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜