I'm having trouble grasping the proper way to create view models and save that info back to the database using Entity Framework, and I can't seem to find the info I'm looking for, so please forgive me if I have overlooked it.
I came across this post here and he seems to be asking the same question but doesn't get an answer.
My main questions are,
For editing purposes, If I have a ProductModel model
that has a Warranty model
relationship, should I be using virtual property Warranty
in the view model or should I be using int WarrantyId
?
If I should be using a virtual property, why doesn't this code save the Warranty
properly?
Do I need to explicitly flag or populate the Warranty for update?
Please not this does populate my edit view and select lists as intended.
My (simplified) code is setup as follows:
Model:
public int ModelId{ get; set; }
public int ModelNumber { get; set; }
public virtual Warranty Warranty { get; set;}
View Model:
public int ModelId { get; set; }
[Required(ErrorMessage = "Model Number required")]
[StringLength(25, ErrorMessage = "Must be under 25 characters")]
[Display(Name="Model Number")]
public string ModelNumber { get; set; }
//related objects and necesary properties
public virtual Warranty Warranty { get; set; }
public IEnumerable<SelectListItem> WarrantySelectListItems { get; set; }
Controller (GET):
public ActionResult Edit(int? id)
{
//check the id
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//get the model and make sure the object is populated
var model = _modelService.GetModel(id.Value);
if (model == null)
{
return HttpNotFound();
}
//pass our entity (db) model to our view model
var editModelModel = new EditModelModel();
editModelModel.InjectFrom(model);
//warranty select list
editModelModel.WarrantySelectListItems = WarrantySelectList(editModelModel.Warranty.WarrantyId);
//option multi select list
editModelModel.OptionSelectListItems = OptionSelectList();
return View(editModelModel);
}
Controller (POST) (work in progress):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditModelModel editModelModel)
{
if (!ModelState.IsValid)
{
return View(editModelModel);
}
var modelEntity = new Model();
modelEntity.InjectFrom(editModelModel);
_modelService.Update(modelEntity);
_unitOfWork.Save();
return RedirectToAction("Index");
}
View (simplified):
<div class="form-group">
@Html.Label("Warranty", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(x => x.Warranty.WarrantyId, Model.WarrantySelectListItems, "--Select--")
@Html.ValidationMessageFor(model => model.Warranty.WarrantyId)
</div>
</div>
Again, I just want to know the proper/best way to set up these viewmodels and models so the EF is doing as much of the work as possible. I feel like if I have to create a WarrantyId
field, I'm doing something wrong, but maybe that isn't the case.
Thanks in advance. Any insight/help is greatly appreciated.