Mike
Mike

Reputation: 5519

How can I order by a derived property in linq to sql?

I have a property called Total that is derived from other values on my data object. When I try to use this property in an order by statement in linq to sql I get: The member '...' has no supported translation to SQL. Which makes sense but is there a work around for this scenario? Thanks!

Upvotes: 0

Views: 600

Answers (1)

Mark Coleman
Mark Coleman

Reputation: 40863

You could invoke the query and than do your OrderBy() clause.

var items = context.Tables.ToList().OrderBy(x=>x.Total);

You can do this since after you invoke .ToList() you will be using linq to objects.

As Broken mentions this might not work in all cases, another possible solution would be to reproduce your total calculation in your .Select()

note, my syntax might be off a bit, dont have VS with me :)

var items = context.Tables.Select(t=> new {t.Item1, Total=(t.Price + t.Tax)})
                          .OrderBy(t=>t.Total);

Now granted with this type of projection you wont end up with a Table any more but might be an option.

Upvotes: 2

Related Questions