将 属性 添加到 ViewModel 中的模型

Adding a property to a Model in the ViewModel

与模特

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 行中,以便在视图中可以看到,什么是最好的将年龄 属性 添加到每一行的方法?

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

    public string Age      { get; set; }

您可以使用 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; }
}

你可以制作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{}

}