【问题标题】:Adding a property to a Model in the ViewModel在 ViewModel 中向模型添加属性
【发布时间】:2018-07-30 19:06:27
【问题描述】:

与模型

public class Person {
    public string Forename { get; set; }
    public string Surname  { get; set; }
    public string DOB      { get; set; }
}

我有一个 ViewModel,我将通过它传递给 View

public class PersonViewModel {
    public IQueryable<Person> PersonVM { get; set; }
    public string sometext{ get; set; }
}

例如,如果我想在控制器代码中计算年龄并将其存储在 IQueryable 中的每个 Person 行中以便可以在视图中看到,那么添加 Age 属性的最佳方法是什么到每一行?

我猜我不必像这样在Person 模型中包含虚假属性

    public string Age      { get; set; }

【问题讨论】:

  • 您是否使用过任何将视图模型映射到自动映射器等模型的映射库?
  • 这个年龄是保存在数据库中还是只用于运行时计算?

标签: asp.net-core-mvc entity-framework-core razor-pages


【解决方案1】:

您可以使用 NotMapped 属性将属性从数据库映射中排除。

public class Person
{
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string DOB { get; set; }
    [NotMapped]
    public string Age { get; set; }
}

【讨论】:

  • 将这两个答案混合在一起可以解决其他一些问题,这就是我所做的。
【解决方案2】:

您可以创建Age 属性set private 并将您的逻辑写入get 以在运行时计算它。

public class Person {
  public string Forename { get; set; }
  public string Surname  { get; set; }
  public string DOB      { get; set; }
  public string Age {
                      get{
                            //.... you logic
                      }
                      private set{}

}

【讨论】:

  • 将这两个答案混合在一起可以解决其他一些问题,这就是我所做的。不过只能给一个人打勾,对不起。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多