简体   繁体   中英

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?

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

I was not able to get 'Argo's answer to work initially. After a little playing around I noticed that if i decorated the property (as in WCF), which the following attribute, all worked fine.

[global::System.Runtime.Serialization.DataMemberAttribute()]

As per 'Argo's instructions create a separate file, (for example EmployeeExtension.cs). this should be marked partial as described.

In this file, place the following code:

public partial class Employee 
{
   [global::System.Runtime.Serialization.DataMemberAttribute()]       
   public decimal Salary     
   { 
      get { return Hours*Wage; } 
   } 
}  

Hope this helps….

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 {
    get { return Hours*Wage; }
  }
}

This wasn't working for me with Entity Framework 5. The solution for me was to simply use the [NotMapped] attribute. For more info see Code First DataAnnotations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM