Creating a ViewModel from two EF Models in ASP.Net

2019-05-27 11:17发布

问题:

I have been searching around and really can not find a decent answer on how to build a ViewModel and then fill that with the data from my EF model. The two EF models I want to push into a single ViewModel are:

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

And I would like to build a ViewModel that looks like:

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

I would assume it would be best to create a constructor method in the ViewModel so when NEW is called on it the data is filled but what I can not seem to find or figure out is how I go about filling that data.

回答1:

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