我对这个有点困惑。我阅读了有关MSDN上this文章的元数据类。元数据类是否与asp.net MVC中的ViewModel相同?
它说创建元数据的原因并不是由EF自动生成模型。
因此,这是由EF生成的模型:
namespace Blog.Models
{
using System;
using System.Collections.Generic;
public partial class Article
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Article()
{
this.ArticleTags = new HashSet<ArticleTag>();
this.Comments = new HashSet<Comment>();
}
public int ArticleID { get; set; }
public string PostTitle { get; set; }
public string PostContent { get; set; }
public string PostLinkText { get; set; }
public Nullable<System.DateTime> PostDateTime { get; set; }
public Nullable<int> PostAuthorID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ArticleTag> ArticleTags { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Comment> Comments { get; set; }
public virtual Admin Admin { get; set; }
}
}
,这是条模型元数据类:
public class ArticleMetadata
{
[Display(Name = "Post Title")]
public string PostTitle { get; set; }
[Display(Name = "Content")]
public string PostContent { get; set; }
[Display(Name = "Link Text")]
public string PostLinkText { get; set; }
[Display(Name = "Post Date and Time")]
public DateTime? PostDateTime { get; set; }
[Display(Name = "Post Author")]
public int? PostAuthorID { get; set; }
}
连接使用PartialClasses.cs模型类:
[MetadataType(typeof(ArticleMetadata))]
public partial class Article
{
}
元数据类是否与ViewModel相同?
如果是这样,这些不同之处是什么,应该在我的情况下使用哪一个?
所以,如果我为每个模型创建一个视图模型,那么我可以删除元数据类,对吧? – VSG24
在这种情况下是的。但是您应该创建ViewModel for Views,而不是为每个模型创建ViewModels。一个ViewModel可以使用来自几个Model类的数据。 –
我同意亨克的评论。为了解决这个问题,您可能希望使用映射器将ViewModel属性映射到实体属性,如[AutoMapper](http://automapper.org)。这使您可以使ViewModel独立于实体Model,但您可以轻松地在模型之间来回传递数据,就像您在处理实体模型时一样。只是一个想法。 – Blake