Domanda

I am learning about Code First right now in regards to having a Controller, Model, and View. I want to have a custom value of age however, and I am not sure how to make this "calculation" occur within my Model. I have always been using something like public int Age {get; set; } without any sort of calculations occurring on that variable, but now I wish to do something to that variables value based off another variables value, such as Age = CurrentDate-BirthDate.

Since I am still new to the concept of {get; set;}, I think I am just confused on how to keep that expression while updating Age.

Here is what my model looks like (just the variables), and as mentioned, I want to do an equation off BirthDate's user-input value to set Age's value rather than get it from the user.

public class Actor
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime Age;      
        public decimal NetValue { get; set; }
    }

*On a side note, should I use an "int" or "DateTime" for Age? DateTime was used in a tutorial thus why it is in my code.

Thank you very much!

È stato utile?

Soluzione

For a read-only calculated property, all you need is a manual getter. Something like this:

public int Age
{
    get { return (DateTime.Now - BirthDate).TotalDays / 365; }
}

Note that this "dividing by 365" is a very primitive way of actually calculating the years. There are better ways. This is purely a small example to demonstrate a calculated property on a model.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top