【问题标题】:View Model implementation - less fields than in entities查看模型实现 - 字段少于实体
【发布时间】:2013-11-29 11:32:00
【问题描述】:

我有两个实体:PersonQuote(一对多关系)

人物:

 public class Person
 {
    public int PersonID { get; set; }

    [Required]
    [StringLength(20]
    public string Name { get; set; }

    [StringLength(30]
    public string Relation { get; set; }

    public byte[] Image { get; set; }

    [StringLength(50)]
    public string ImageMimeType { get; set; }

    public virtual ICollection<Quote> Quotes { get; set; }
}

引用:

public class Quote
{
    public int QuoteID { get; set; }

    public int PersonID { get; set; }

    [Required]
    [StringLength(200)]
    public string QuoteName { get; set; }

    [StringLength(400)]
    public string Context { get; set; }

    public DateTime? Date { get; set; }

    public virtual Person Person { get; set; }
}

我想创建一个 ViewModel 来以短格式显示引号 - 我只需要几个属性 - Person NameQuoteNamePerson Image。我可以做一些随意的事情,就像他们在每个 ASP.NET MVC 教程中展示的那样:

 public class QuoteViewModel
 {
    public IEnumerable<Quote> Quotes { get; set; }
 }

有没有更好的方法,而不是使用 Quote 类型创建 IEnumerable 并加载所有属性?

如何创建QuoteShort 模型并将QuoteViewModel 设置为IEnumerable&lt;QuoteShort&gt; QuotesShort

在控制器中,我会将存储库中的每 3 个字段映射到 QuoteShort 并将其添加到 QuotesShort IEnumerable (即使我不知道如何将它们持久化到 QuotesShort IEnumerable )

一些例子表示赞赏。

【问题讨论】:

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


    【解决方案1】:

    您可以使用您需要的几个属性创建一个QuoteShort ViewModel,然后让您的视图期望IEnumerable&lt;QuoteShort&gt; 作为其模型。您不必将其包装在另一个容器中。

    如果你有这个:

    public class QuoteShort{
    
        public Person Person {get;set;}
        public string Name {get; set;}
        // etc
    }
    

    您可以在控制器中执行此操作:

    var quotes = //however you get your list of quotes
    var model = (from q in quotes select new QuoteShort
                    { Person = q.Person, Name = q.Name /*etc*/ }).ToList();
    
    return View(model);
    

    【讨论】:

    • 关于期望 IEnumerable 的视图的良好提示,并感谢 linq 示例。实体框架进行了适当的内部连接。
    【解决方案2】:

    类似的东西呢

    public class QuotesShortViewModel
    {
        public IEnumerable<QuoteShortViewModel> QuotesShort { get; set; }
    }
    
    public class QuoteShortViewModel
    {
        // ... the properties you need
    }
    

    创建一个View,它接收一个 QuotesShortViewModel 并遍历列表,根据您的喜好呈现短引号。

    AutoMapper 可用于在控制器中的模型和视图模型之间进行映射。

    【讨论】:

    • 使用 AutoMapper 时,您可以使用 Project().To() 扩展来仅从数据库中检索所需的属性。
    猜你喜欢
    • 2017-08-22
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多