views:

769

answers:

3

Suppose I have an employee object with the following properties:

Name - string Hours - single Wage - single

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?

+6  A: 

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.

JoshJordan
Excellent! I'd been creating shadow classes, which was utterly painful. Much thanks
Chris B. Behrens
This doesn't seem to work with Linq to Entities since it's not defined in the actual data model. Is there a way to define a calculated field in the *.edmx?
AaronLS
Can you be more specific than "doesn't seem to work"? If you're referring to columns with computed values at the database level, thats a whole different beast.
JoshJordan
+2  A: 

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

Argo
+2  A: 

You can implement the property in the entity class. The entity framework will generate partial classes allowing you to add members to the class. Add a class like this to your code:

public partial class Employee {
  public Single Salary {
    return Hours*Wage;
  }
}
Martin Liversage