I want to know a good way of converting the Model
to ViewModel
and ViewModel
to Model
without AutoMapper
or something similar, because I want to understand what is behind and learn how to do it myself. Of course, by Model I mean the classes generated by EF.
I made something like this so far, but have some issues when nested classes are involved:
// to VM
public static Author ToViewModel(EntityAuthor author)
{
if (author == null)
return null;
Author result = new Author();
result.Id = author.ATH_ID;
result.FirstName = author.ATH_FirstName;
result.LastName = author.ATH_LastName;
return result;
}
public static BlogPost ToViewModel(EntityBlogPost post)
{
if (post == null)
return null;
Experiment result = new Experiment();
result.Id = post.BP_ID;
result.Title = post.BP_Title;
result.Url = post.BP_Url;
result.Description = post.BP_Description;
result.Author = ToViewModel(post.Author);
return result;
}
// from VM
public static EntityAuthor ToModel(Author author)
{
if (author == null)
return null;
EntityAuthor result = new EntityAuthor();
result.ATH_ID= author.Id;
result.ATH_FirstName = author.FirstName;
result.ATH_LastName = author.LastName;
return result;
}
public static EntityBlogPost ToModel(BlogPost post)
{
if (post == null)
return null;
EntityBlogPost result = new EntityBlogPost();
result.BP_ID = post.Id;
result.BP_Title = post.Title;
result.BP_Url = post.Url;
result.BP_Description = post.Description;
result.Author = ToModel(post.Author);
return result;
}
Note: The EntityBlogPost
holds the Foreign key to the EntityAuthor
. One issue that I face now is when I want to edit a BlogPost, its corresponding entity requires the author's foreign key: "BP_ATH_ID" to be set, but this is '0' since the author of the edited post is 'null', because I don't want to http-post the author. Still, the author needs to be in the view-model because I want to display it (during http-get). Here is my controller to understand better (the view is not of importance):
// GET: I make use of Author for this
public ActionResult Edit(int id)
{
return View(VMConverter.ToViewModel(new BlogPostService().GetByID(id)));
}
//
// POST: I don't make use of Author for this
[HttpPost]
public ActionResult Edit(BlogPost input)
{
if (ModelState.IsValid)
{
new BlogPostService().Update(VMConverter.ToModel(input));
return RedirectToAction("List");
}
return View(input);
}
At the moment I have some Services behind my controller which work only over the Model
(as you can see in my code). The intent was to reuse this "service layer" for other applications as well.
public void Update(EntityBlogPost post)
{
// let's keep it simple for now
this.dbContext.Entry(post).State = EntityState.Modified;
this.dbContext.SaveChanges();
}
Ok, so back to my question. What would be a nice way to handle this transition Model->ViewModel and back?