I\'m porting a subsystem from NHibernate to Entity Framework and want to see the best way to port the following query to EF.
var d
The following query do exactly what I need with just one query to the database:
var accountBalance = context
.AccountBalanceByDate
.Where(a =>
a.Date == context.AccountBalanceByDate
.Where(b => b.AccountId == a.AccountId && b.Date < date).Max(b => b.Date));
Thanks @AgentShark for the help.
The code is on GIST: https://gist.github.com/sergiogarciadev/9f7bd31a21363ee0b646
Finally, a solution. :)
var date = DateTime.Now; // It can be any day
var lastBalances = (from a in context.AccountBalanceByDate
where a.Date < date
group a by new {a.AccountId} into g
select g.OrderByDescending(a => a.Date).FirstOrDefault() into r
select new
{
Id = r.Id,
AccountId = r.AccountId,
Date = r.Date,
Balance = r.Balance
}).ToList();
You wanted it in LINQ, but personally, I might of kept the SQL for maintainability.