我對這個有點困惑。我閱讀了有關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