MVC controller with ViewModel method for updating EF objects

After reading a bunch of best practices, I now use the viewmodel that is configured for each view, and my controller methods pass the viewmodels to the view and then update the db.

I have GET methods that work correctly using a LINQ projection, but I'm not sure what to do in the POST method. If my view model contains only properties updated by its view, but a record already exists in the database for this keyword, how can I update my EF model with the viewmodel properties without getting each property in the EF model every time?

Here is my code:

ViewModel

public class GeneralViewModel { public string Title { get; set; } public decimal? Proposal_Type_ID { get; set; } public string User_Facility_ID { get; set; } public IEnumerable<SelectListItem> ProposalTypes { get; set; } } 

controller

  public ActionResult General(int id) { var context = new PASSEntities(); var model = (from a in context.Proposals where a.ID == id select new GeneralViewModel() { User_Facility_ID = a.User_Facility_ID, Title = a.Title, Proposal_Type_ID = a.Proposal_Type_ID }).SingleOrDefault(); var proposalTypes = context.Proposal_Types.Where(m => m.User_Facility_ID == model.User_Facility_ID).ToList(); model.ProposalTypes = proposalTypes.Select(m => new SelectListItem { Value = m.ID.ToString(), Text = m.Description }).ToList(); return PartialView(model); } [HttpPost] public ActionResult General(int id, GeneralViewModel model) { try { var context = new PASSEntities(); var proposal = context.Proposals.Find(id); proposal.Title = model.Title; proposal.Proposal_Type_ID = model.Proposal_Type_ID; context.Entry(proposal).State = System.Data.EntityState.Modified; context.SaveChanges(); return PartialView(); } catch { return View(); } } 

My post works, but I donโ€™t feel that this is the best way to do this. The reason I did this was because when I just introduced the EF Proposal model and matched its properties with the viewmodel properties, it changed the value of User_Facility_ID to null because I did not use it in my form.

So I'm just looking for the best way to do POST.

+4
source share
1 answer

What you do is the โ€œrightโ€ method, you need to get your object out of context, make updates, and then save the changes.

When you use a mapping tool, such as AutoMapper, make sure that you exclude key fields that you do not want to update from the map.

+2
source

Source: https://habr.com/ru/post/1501922/


All Articles