如何处理ViewModel中的集合?

时间:2012-08-09 16:45:39

标签: asp.net-mvc nhibernate mapping viewmodel parent-child

我想我几乎已经弄明白了。这个问题是.NET MVC应用程序的上下文。

我的实体(我很快就会切换到 Fluent nHibernate

[Serializable]
[Class(Schema = "dbo", Table = "LiveMedia")]
[Cache(1, Usage = CacheUsage.ReadWrite)]
public class Media : NhBase<Media>
{
    [Id(Name = "Id", Column = "ID"), Generator(1, Class = "native")]
    public virtual int Id { get; set; }

    [Property]
    public virtual string Title { get; set; }

    [Property]
    public virtual string Description { get; set; }

    [Property(Column = "TypeID")]
    public virtual MediaType MediaType { get; set; }

    [Property]
    public virtual DateTime CreatedAt { get; set; }

    [Property]
    public virtual DateTime UpdatedAt { get; set; }

    [Property]
    public virtual string EmbedUrl { get; set; }

    [Property]
    public virtual string ThumbnailUrl { get; set; }

    [Property]
    public virtual string S3Filename { get; set; }

    [XmlIgnore, Set(0, Table = "LiveCollectionMedia", Schema = "dbo", Cascade = CascadeStyle.AllDeleteOrphan, Lazy = true, Inverse = true), Key(1, Column = "MediaID"), OneToMany(2, Class = "BanffCentre.Business.Data.Live.MediaCollection, BanffCentre")]
    public virtual ISet<MediaCollection> Collections { get; set; }

    [XmlIgnore, Set(0, Table = "LiveMediaCategory", Schema = "dbo", Cascade = CascadeStyle.SaveUpdate, Lazy = true), Key(1, Column = "MediaID"), ManyToMany(2, Class = "BanffCentre.Business.Data.Live.Tag, BanffCentre", Column = "CategoryID")]
    public virtual ISet<Tag> Tags { get; set; }

    public Media()
    {
        Collections = new HashedSet<MediaCollection>();
        Tags = new HashedSet<Tag>();
    }
}

我的ViewModel:

public class MediaAudioViewModel
{
    public int? Id { get; set; }

    [Required]
    public string Title { get; set; }

    public string Description { get; set; }
    public MediaType MediaType { get; set; }
    public string ThumbnailUrl { get; set; }
    public IList<Tag> Tags { get; set; }
    public string S3Filename { get; set; }
    public HttpPostedFileBase AudioFile { get; set; }
}

问题:

我知道我的ViewModel中不应该有“Tag”实体的集合:

public IList<Tag> Tags { get; set; }

所以我想将 TagViewModel 映射到此?喜欢这个?

public IList<TagViewModel> Tags { get; set; }

如果这是多对多关系,我想在我开始创建视图时从 TagViewModel 映射 MediaViewModel 对于标签?

我想是的......我觉得这个抽象的东西有点疯狂。只是希望快速确认!

感谢。

修改

This post似乎回答了我的问题。我刚发现它。我仍然对任何其他想法感兴趣。

1 个答案:

答案 0 :(得分:1)

在做了一些阅读之后,我决定我的视图模型应该包含其他ViewModel的集合。使用 AutoMapper 我通常可以为我完成此操作。

Mapper.CreateMap<MediaDto, MediaVideoViewModel>();
Mapper.CreateMap<TagDto, TagViewModel>();
var videoModel = Mapper.Map<MediaDto, MediaVideoViewModel>(mediaDto);