How to Map sum property (like TotalPrice) in Entity Framework Code First
I use entity framework 4.1 code first. And I have classic sample: Order and OrderLines. Each OrderLine has its own price and I'd like to have property TotalPrice on Order.
I'm not sure now to declare TotalPrice property. I can define it as readonly with linq sum, but when each time I add it to the resultset, it must fetch all orderlines from db to sum it's prices.
I'm thinking about solution, which store totalprice into database (for queries) and recalculate only before order save (or if orderline changes), but I don't how to do that.
How to handle scenarios like this in EF?
Thanks fo开发者_开发问答r suggestions Petr
For the sake of simplicity, I would recommend not storing and just adding a calculation method to a partial class. We've done this before with a *Methods
suffix. For example:
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
}
}
My reason to store total price is performance. I already have contract class, which contain Orders (and also has TotalPrice property). When I do not store total price, and want select list of contracts (to grid for example), it then must always read all orders and it's lines.
精彩评论