Question

I have a table of invoices. My service layer knows how to calculate the invoice Total for one invoice, but if I want to filter a set of invoices by Total, the LINQ query fails because there is "No Supported Translation in SQL". This happens because nested query cannot be performed for every invoice record. What is the right way to work around it?

Each invoice Total is determined by summing calculated line totals from an InvoiceLines table which involve discounts, literally:

public decimal Total
{
    get
    {
        return Lines.Sum(l => l.LineTotal); // Lines provided by repository
    }
}

I prefer not to duplicate business logic in my database that is already in my service layer, which involves discounting line items that influence the invoice total. But I don't see any way other than caching the invoice Total in a database column which I can directly filter on.

Invoices are immutable, so it shouldn't lead to any data integrity problems, but I hate duplicating data. I could use a view to display the invoice total, but then my repository is performing service-layer functions.

Was it helpful?

Solution 2

Solved:

  1. Added a cached total value in my model that I can either set (thereby caching it) or calculated the total from the model's lazy-loaded items.
  2. Added a view in my database to calculate the total, which is a duplication of logic already in my business logic. But it works.
  3. Bind the view's total value to my model, setting the cached total value.

Now I can filter my data on totals, which are calculated by the database and cached in my models.

OTHER TIPS

Is Total an added property to a LINQ entity? If it is, you can't use the Total property; that's specifically not supported. It's hard to put reused logic all in one place in a LINQ query that goes against the database... If you do a root query, then perform the extra task after the query is executed (which can be easily done calling ToList()), all processing after this would be with LINQ to Objects, and you can do whatever you want.

HTH.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top