我想知道一种将Model
toViewModel
和ViewModel
to Model
withoutAutoMapper
或类似东西转换的好方法,因为我想了解背后的内容并学习如何自己做。当然,模型是指由 EF 生成的类。
到目前为止,我做了这样的事情,但是在涉及嵌套类时遇到了一些问题:
// 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;
}
注意:EntityBlogPost
持有EntityAuthor
. 我现在面临的一个问题是,当我想编辑一篇博客文章时,它的对应实体需要设置作者的外键:“BP_ATH_ID”,但这是“0”,因为编辑后的帖子的作者是“空”,因为我不想http-post作者。不过,作者需要在视图模型中,因为我想显示它(在 http-get 期间)。这是我的控制器以更好地理解(视图并不重要):
// 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);
}
目前,我的控制器后面有一些服务Model
,它们只能在(如您在我的代码中看到的那样)工作。其目的是将这个“服务层”也用于其他应用程序。
public void Update(EntityBlogPost post)
{
// let's keep it simple for now
this.dbContext.Entry(post).State = EntityState.Modified;
this.dbContext.SaveChanges();
}
好的,回到我的问题。处理这种转换模型->视图模型并返回的好方法是什么?