Subquery with Entity Framework

前端 未结 2 1185
野性不改
野性不改 2021-01-17 11:38

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         


        
相关标签:
2条回答
  • 2021-01-17 11:57

    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

    0 讨论(0)
  • 2021-01-17 12:16

    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.

    0 讨论(0)
提交回复
热议问题