Subquery with Entity Framework

c# entity-framework nhibernate sql sql-server

Question

I want to know the best approach to convert the following query to EF because I'm moving a subsystem from NHibernate to Enterprise Framework.

var date = DateTime.Now; // It can be any day
AccountBalanceByDate abbd = null;
var lastBalanceDateByAccountQuery = QueryOver.Of<AccountBalanceByDate>()
    .Where(x => x.AccountId == abbd.AccountId && x.Date < date)
    .Select(Projections.Max<AccountBalanceByDate>(x => x.Date));

var lastBalances = session.QueryOver<AccountBalanceByDate>(() => abbd)
    .WithSubquery.WhereProperty(x => x.Date).Eq(lastBalanceDateByAccountQuery)
    .List();

The class of the account balance is:

public class AccountBalanceByDate
{
    public virtual int Id { get; set; }
    public virtual int AccountId { get; set; }
    public virtual DateTime Date { get; set; }
    public virtual decimal Balance { get; set; }
}

As for the table:

CREATE TABLE [dbo].[AccountBalanceByDate]
(
    [Id]        int NOT NULL,
    [AccountId] int NOT NULL,
    [Date]      [datetime] NOT NULL,
    [Balance]   [decimal](19, 5) NOT NULL,

    PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )
)

(Using numerical ids for easier understanding) Here is an example of data:

Id | Date        | Account | Balance
------------------------------------
 1 | 2014-02-01  | 101     | 1390.00000
 2 | 2014-02-01  | 102     | 1360.00000
 3 | 2014-02-01  | 103     | 1630.00000
 4 | 2014-02-02  | 102     | 1370.00000
 5 | 2014-02-02  | 103     | 1700.00000
 6 | 2014-02-03  | 101     | 1490.00000
 7 | 2014-02-03  | 103     | 1760.00000
 8 | 2014-02-04  | 101     | 1530.00000
 9 | 2014-02-04  | 102     | 1540.00000

The entity with the account balance at a given time is AccountBalanceByDate. A day without a transaction will not have a AccountBalanceByDate, thus we must look at the preceding days to determine the account's balance.

If I run a query using the date 2014-02-01, I ought to receive:

 No results

If I run a query with the date 2014-02-02, I ought to receive:

 1 | 2014-02-01  | 101     | 1390.00000
 2 | 2014-02-01  | 102     | 1360.00000
 3 | 2014-02-01  | 103     | 1630.00000

If I run a query using the date 2014-02-03, I ought to receive:

 1 | 2014-02-01  | 101     | 1390.00000
 4 | 2014-02-02  | 102     | 1370.00000
 5 | 2014-02-02  | 103     | 1700.00000

If I run a query using the date 2014-02-04, I ought to receive:

 4 | 2014-02-02  | 102     | 1370.00000
 6 | 2014-02-03  | 101     | 1490.00000
 7 | 2014-02-03  | 103     | 1760.00000

If I run a query using the date 2014-02-05, I ought to receive:

 7 | 2014-02-03  | 103     | 1760.00000
 8 | 2014-02-04  | 101     | 1530.00000
 9 | 2014-02-04  | 102     | 1540.00000

Although I can accomplish this with raw SQL in Entity Framework, it is not desirable.

using (var context = new DbContext()) 
{ 
    var lastBalances = context.AccountBalanceByDate.SqlQuery(
        @"SELECT
            *
        FROM 
            [AccountBalanceByDate] AB
        WHERE
            DATE = (
                SELECT
                    MAX(Date) 
                FROM 
                    [AccountBalanceByDate]
                WHERE
                    AccountId = AB.AccountId AND DATE < @p0
            )", date).ToList(); 
}

Is it feasible to access the database only once while using linq, as opposed to multiple times when using raw SQL and NHibernate?

UPDATE:

Fixed answers to the query.

SQL displaying the example GIST query: https://gist.github.com/LawfulHacker/275ec363070f2513b887

Sample of an entity framework from GIST is https://gist.github.com/LawfulHacker/9f7bd31a21363ee0b646.

1
11
10/6/2016 7:45:40 PM

Accepted Answer

The following database query performs what I need with just one query:

var accountBalance = context
    .AccountBalanceByDate
    .Where(a => 
        a.Date == context.AccountBalanceByDate
             .Where(b => b.AccountId == a.AccountId && b.Date < date).Max(b => b.Date));

Thanks for the assistance, @AgentShark.

The code is https://gist.github.com/LawfulHacker/9f7bd31a21363ee0b646 on GIST.

22
6/8/2017 2:09:06 PM

Popular Answer

There is now a resolution.

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, however I might have maintained the SQL because it is more maintainable.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow