我想使用视图模型来代替域模型。我有这些视图模型类:
public class ArticleDescriptionViewModel
{
public string Title { get; set; }
public DateTime DateCreated { get; set; }
}
public class HomePage
{
public List<ArticleDescriptionViewModel> Articles { get; set; }
}
在域模型中我得到了:
public class ArticleDescription
{
public string Title { get; set; }
public DateTime DateCreated { get; set; }
}
这种服务方式:
public List<ArticleDescription> GetArticlesDescription()
{
var articleDescription= from a in _ctx.Articles
select new ArticleDescription
{ Title = a.Title, DateCreated = a.DateCreated };
return articleDescription.ToList();
}
在控制器中我想将我的视图模型类中的列表与我的域模型类返回的列表相匹配。
public ActionResult Index()
{
HomePage HomePageInstance = new HomePage();
HomePageInstance.Articles = _repo.GetArticlesDescription();
return View(HomePageInstance);
}
我有一个错误:
&#34;无法隐式转换类型System.Collections.Generic.List(DBayonaCode.Domain.Services.Models.ArticleDescription)&#39; to&#39; System.Collections.Generic.List(DBayonaCode.Models.ArticleDescriptionViewModel)&#39;&#34;
但这两个类是相同的吗?我做错了什么。我感谢你的帮助吗?
答案 0 :(得分:0)
ArticleDescription
和ArticleDescriptionViewModel
是两种不同的类型,因此它们之间没有隐式转换。您需要将域模型对象映射到视图模型对象,您可以手动或使用 AutoMapper
您可以编写这样的扩展方法来进行映射:
public static class Mappings
{
public static ArticleDescriptionViewModel ConvertToView(this ArticleDescription article)
{
// Mapping Code
// return new ArticleDescriptionViewModel { ... }
}
public static List<ArticleDescriptionViewModel> ConvertToViews(this List<ArticleDescription> articles)
{
List<ArticleDescriptionViewModel> articleViews = new List<ArticleDescriptionViewModel>();
foreach (ArticleDescription article in articles)
{
articleViews.Add(article.ConvertToView())
}
return articleViews;
}
}
答案 1 :(得分:0)
虽然MVC默认项目模板只提供一个模型文件夹,因此隐含地提出了模型是一回事的想法,实际上ASP.NET MVC应用程序中可能涉及三种类型的数据模型:
- Domain model objects will be passed from and to a middle tier services interfacing with databases.
- View Model objects are those that the Controller pass to the View.
- Input model objects are those that the default modelBinder or some custom modelBinder generates from the view, although in many cases the input models are the same view model objects.
希望它有所帮助。