Suppose I have an Employee object with the following properties:
string Name { get; } float Hours { get; } float Wage { get; }
I want to add a property, Salary, which equals Hours * Wage. In an ordinary business object, I would simply code that up in the property, but this would presumably wiped out if the class needed to be regenerated.
Is there an EF standard way to implement this without going through the trouble of mapping it to a database entity?
The Entity Framework Core Fluent API HasComputedColumnSql method is used to specify that the property should map to a computed column. The method takes a string indicating the expression used to generate the default value for a database column.
The Entity Framework Core Fluent API ValueGeneratedOnAdd method indicates that the value for the selected property is generated by the database whenever a new entity is added to the database. Therefore, the property should be ignored by EF Core when constructing an INSERT statement.
Right-click the column for which you want to specify a computed column formula and select Delete. Select OK. Add a new column and specify the computed column formula by following the previous procedure to add a new computed column.
The Entity Framework Core Fluent API ValueGeneratedNever provides a way to specify that the value for the selected property should never be generated automtically by the database. This is useful if you want to circumvent the database's default behaviour.
If i remember correctly the classes created by the EF are partial. So you could possibly add another file containing another partial class (same namespace, same classname of course) which than implements the property
public single Salary { get { return this.Hours * this.Wage; } }
Should do the trick (if those singles are not nullable, mind you!)
Indeed. Create a separate file, for instance, EmployeeExtension.cs.
In this file, place the following code:
public partial class Employee { public decimal Salary { get { return Hours * Wage; } } }
LINQ to SQL and Entity Framework classes are generated with the partial keyword to allow you to split the definition over many files, because the designers knew that you will want to add members to the class that aren't overwritten by continually autogenerating the base source file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With