1

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; }
2
  • Did you used any mapping library which map viewmodel to model like automapper ? Commented Feb 20, 2018 at 13:42
  • Is this Age saved in database or only used to calculate at run time ? Commented Feb 20, 2018 at 13:42

2 Answers 2

1

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Mixing both of these answers together solves a few other problems, so that's what I've done.
1

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

}

1 Comment

Mixing both of these answers together solves a few other problems, so that's what I've done. Can only give tick answer to one person though, sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.