Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculated properties in Entity Framework

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?

like image 420
Chris B. Behrens Avatar asked Jul 15 '09 14:07

Chris B. Behrens


People also ask

How can we specify computed generated column in Entity Framework?

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.

What is ValueGeneratedOnAdd?

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.

How do I add a calculated field in SQL Server?

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.

What is ValueGeneratedNever?

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.


2 Answers

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!)

like image 40
Argo Avatar answered Sep 22 '22 09:09

Argo


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.

like image 62
JoshJordan Avatar answered Sep 24 '22 09:09

JoshJordan