How to map a sum property (e.g. TotalPrice) in Entity Framework Code First

First I use the framework code 4.1. And I have a classic pattern: Order and OrderLines. Each OrderLine has its own price, and I would like to have the TotalPrice on Order property.

Now I'm not sure to declare a TotalPrice property. I can define it as readonly with the sum of linq, but when every time I add it to the result set, it must extract all order lines from db to sum them up.

I am thinking of a solution that stores totalprice in the database (for queries) and is only recalculated until the order is saved (or if the order line changes), but I do not.

How to handle scripts like this in EF?

Thanks for the suggestions of Petr

+5
source share
2 answers

For simplicity, I would recommend not storing and just adding a calculation method to a partial class. We did this before with a suffix *Methods. For instance:

Order.cs:

public partial class Order 
{       
   public ICollection<OrderLine> OrderLines { get;set; }
   //Other EF Properties
}

OrderLine.cs:

public partial class OrderLine 
{       
   public double Price { get;set; }
   //Other EF Properties
}

OrderMethods.cs

public partial class Order 
{
    public double GetTotalPrice() 
    {
        // Total price calculation
    }
}
0
source

My reason for keeping the overall price is performance. I already have a contract class that contains Orders (and also has a TotalPrice property). When I do not store the total price and want to select a list of contracts (for example, for the grid), he should always read all orders and lines.

0
source

All Articles