Home > OS >  Set value on entry to the database
Set value on entry to the database

Time:09-28

I am trying to set a value of a property inside of my model on entry to the database automatically whenever the model is created, however this needs to rely on the value of two other columns based on it.

Essentially I am trying to automatically calculate the BMI of an individual based on the models height and weight.

var person = new PersonBmi
{
  Height = 183,
  Weight = 72
}

_context.PersonBmis.Add(person);

_context.SaveChanges();

Now what I was hoping to achieve is that when this model is created and inserted into the database I would be able to calculate the value of the bmi within the model using a method which I have already created without having to call it everywhere.

Here is my BMI calculation method:

public static double CalculateBmi(double height, double weight)
{
    return weight / Math.Pow(height / 100.0, 2);
}

I've tried to use the getters and setters but unfortunately due to me not putting anything within the Bmi property I am unable to get it to set. I don't know if the models have a lifecycle hook which I can do or whether I need to do this within the db context and see if the model has been created / modified.

Currently, I am doing the following:

var height = 183;
var weight = 73;

var person = new PersonBmi
{
  Height = height,
  Weight = weight,
  Bmi = PersonBmi.CalculateBmi(height, weight)
}

Which as you can tell doesn't read the best.

CodePudding user response:

I would suggest using the [NotMapped] on a get only derived property to allow the model to be saved to the database without the derived value

As mentioned in the comments, you probably don't want to risk this derived value going out of date. Something like:

public class PersonBmi
{
    public double Height { get; set; }

    public double Weight { get; set; } 

    [NotMapped]
    public double Bmi => weight / Math.Pow(height / 100.0, 2);
}
  • Related