Adding a property to a Model in the ViewModel

asp.net-core-mvc entity-framework-core razor-pages

Question

With the Model

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

I have a ViewModel which I'll be passing through to the View

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

If, for example, I wanted to calculate the age in the controller code and store it against each Person row in the IQueryable so it could be seen in the View, what's the best way of adding an Age property to each row?

I'm guessing that I don't have to include a fake property in the Person model like so

    public string Age      { get; set; }
1
1
2/20/2018 12:05:22 PM

Accepted Answer

You can use the NotMapped attribute which will exclude the property from database mapping.

public class Person
{
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string DOB { get; set; }
    [NotMapped]
    public string Age { get; set; }
}
1
2/20/2018 12:16:56 PM

Popular Answer

You can make Age property set private and write your logic in get to calculate it at run time.

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{}

}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow