Creating a ViewModel from two EF Models in ASP.Net MVC5

人盡茶涼 提交于 2019-12-06 11:34:26

This is a tightly coupled approach as your view models are coupled to your domain models. I personally do not prefer this way. I would go for another mapping method which maps from my domain model to viewmodel

If you really want the constructor approach, You may pass the Section object to the constructor and set the property values.

public class SectionViewModel
{
    public SectionViewModel(){}
    public SectionViewModel(Section section)
    {
       //set the property values now.
       Title=section.Title;
       HasLogo=(section.Logo!=null && (section.Logo.ID>0)); 
    }

    public Int16 SectionID { get; set; }    
    public bool HasLogo { get; set; } 
    public string Type { get; set; }
    public string Title { get; set; }
    public string Synopsis { get; set; }
}

and when you want to create your view model object,

Section section=repositary.GetSection(someId);
SecionViewModel vm=new SectionViewModel(section);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!