【问题标题】:Creating a ViewModel from two EF Models in ASP.Net MVC5在 ASP.Net MVC5 中从两个 EF 模型创建 ViewModel
【发布时间】:2013-12-25 18:50:38
【问题描述】:

我一直在四处寻找,真的找不到关于如何构建 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 时,数据已被填充,但我似乎无法找到或弄清楚如何填充该数据.

【问题讨论】:

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


    【解决方案1】:

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

    如果你真的想要构造函数的方法,你可以将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);
    

    【讨论】:

    • 我猜这与coupling 没什么关系。为什么你不喜欢你的视图模型来显示域模型的属性?视图中还有什么可显示的?
    • 您的视图模型与域模型(构造函数)紧密耦合,除非您使用接口。可以让视图模型显示域模型的属性。但是在构造函数中使用域模型实例使其与域模型耦合。如果你想改变你的数据访问层(使用领域模型),你也需要改变你的 viewmodel 代码
    • 如果你这么说,我同意。 :)
    • 您建议如何以松散耦合的方式进行操作?此外,如果我的数据库中有 100 行,我该如何填充所有数据。我对GetSection(someID) 的理解是它只返回一行。
    • @MatthewVerstraete GetSection 返回 Section 的单个对象,映射方法将读取该对象的属性值并设置为 viewmodel 实例的相应属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2014-10-26
    相关资源
    最近更新 更多