Asp.net core mvc 向ViewModel中的模型添加特性

Asp.net core mvc 向ViewModel中的模型添加特性,asp.net-core-mvc,entity-framework-core,razor-pages,Asp.net Core Mvc,Entity Framework Core,Razor Pages,用模型 public class Person { public string Forename { get; set; } public string Surname { get; set; } public string DOB { get; set; } } 我有一个ViewModel,我将通过它进入视图 public class PersonViewModel { public IQueryable<Person> PersonV

用模型

public class Person {
    public string Forename { get; set; }
    public string Surname  { get; set; }
    public string DOB      { get; set; }
}
我有一个ViewModel,我将通过它进入视图

public class PersonViewModel {
    public IQueryable<Person> PersonVM { get; set; }
    public string sometext{ 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
属性
设置为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{}

}

您是否使用过将viewmodel映射到automapper之类的模型的映射库?这个年龄是保存在数据库中还是仅用于在运行时计算?将这两个答案混合在一起解决了一些其他问题,所以这就是我所做的。抱歉,我只能给一个人打勾回答。将这两个答案混合在一起可以解决其他一些问题,所以我就是这么做的。
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{}

}