Entity Framework calculated properties

.net calculated-columns entity-framework

Question

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?

1
29
12/6/2012 1:20:26 AM

Accepted Answer

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.

51
12/6/2012 1:23:35 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow