c# - View 模型实现 - 字段少于实体

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

我有两个实体: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 Name , QuoteNamePerson Image .我可以做一些随意的事情,就像他们在每个 ASP.NET MVC 教程中展示的那样:

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

有没有比创建类型为 Quote 的 IEnumerable 更好的方法?并加载所有属性?

如何创建 QuoteShort模型与制作QuoteViewModel作为IEnumerable<QuoteShort> QuotesShort .

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

一些示例表示赞赏。

最佳答案

你可以制作一个QuoteShort ViewModel 只包含您需要的几个属性,然后让您的 View 期待 IEnumerable<QuoteShort>作为它的模型。您不必将其包装在另一个容器中。

如果你有这个:

public class QuoteShort{

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

您可以在 Controller 中执行此操作:

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

关于c# - View 模型实现 - 字段少于实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284785/

相关文章:

c# - 无法转换为 LINQ to Entities 存储表达式

entity-framework - EF 代码优先 : Primary Key same as Foreign Key

c# - Entity Framework 'include' 包含超出应有的内容

c# - Entity Framework 。您的项目引用最新版本 Entity Framework 报错VS2017 MYSQL 8.0.12

c# - 检查表在 SQL Azure 中是否存在

c# - 在 C# 中,按最后一个元素对数组进行排序

c# - 当首选名称也是类型名称时如何命名属性

c# - 如何使用MVC4在部分 View 中调用HtmlHelper方法

asp.net-mvc - 当我不知道内容类型时如何返回文件结果

c# - 更新数据库和更改模型后 Entity Framework 验证错误