从ASP.Net MVC5中的两个EF模型创建ViewModel

时间:2013-12-25 18:50:38

标签: c# entity-framework asp.net-mvc-5 asp.net-mvc-viewmodel

我一直在寻找并且找不到关于如何构建ViewModel然后用我的EF模型中的数据填充它的正确答案。我想要推入单个ViewModel的两个EF模型是:

public class Section
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), HiddenInput]
    public Int16 ID { get; set; }

    [HiddenInput]
    public Int64? LogoFileID { get; set; }

    [Required, MaxLength(250), Column(TypeName = "varchar"), DisplayName("Route Name")]
    public string RouteName { get; set; }

    [Required, MaxLength(15), Column(TypeName = "varchar")]
    public string Type { get; set; }

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

    [HiddenInput]
    public string Synopsis { get; set; }

    [ForeignKey("LogoFileID")]
    public virtual File Logo { get; set; }
}

public class File
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Int64 ID { get; set; }

    [Required, MaxLength(60), Column(TypeName = "varchar")]
    public string FileName { get; set; }

    [Required, MaxLength(50), Column(TypeName = "varchar")]
    public string ContentType { get; set; }
}

我想构建一个类似于:

的ViewModel
public class SectionViewMode
{
    public Int16 SectionID { get; set; }

    public bool HasLogo { get; set; } //Set to True if there is a FileID found for the section
    public string Type { get; set; }
    public string Title { get; set; }
    public string Synopsis { get; set; }
}

我认为最好在ViewModel中创建一个构造函数方法,这样当调用NEW时,数据就会被填充,但我似乎无法找到或弄清楚我是如何填充的那个数据。

1 个答案:

答案 0 :(得分:4)

这是一种紧密耦合方法,因为您的视图模型已与您的域模型相关联。我个人不喜欢这种方式。我会选择另一种映射方法,从我的域模型映射到viewmodel

如果您真的想要构造函数方法,可以将Section对象传递给构造函数并设置属性值。

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; }
}

当您想要创建视图模型对象时,

Section section=repositary.GetSection(someId);
SecionViewModel vm=new SectionViewModel(section);
相关问题