Linq相当于带语句的T-SQL

时间:2018-04-07 08:28:54

标签: c# sql-server linq linq-to-sql

我有以下数据:

accounts

我有以下T-SQL语句:

with acc as 
(
    select 
        acc_number,
        acc_parent,
        acc_number as [root],
        balance
    from 
        accounts
    where 
        acc_parent is null

    union all

    select 
        a.acc_number,
        a.acc_parent,
        acc.[root],
        a.balance
    from 
        accounts a
    inner join 
        acc on a.acc_parent = acc.acc_number
    where 
        a.acc_parent is not null
)
select 
    max([root]) as acc_number,
    sum(balance) as balance
from 
    acc
group by 
    [root];

我想把它翻译成Linq表达式。

我的尝试是

using (AccountsContext context = new AccountsContext())
{
    var roots = context.Accounts
        .Where(r => r.acc_parent == null)
        .Select(r => new
        {
            r.acc_number, 
            r.acc_parent, 
            r.balance
        });
    var accounts = context.Accounts
            .Where(a => a.acc_parent != null)
            .Select(a => new
            {
                a.acc_number, 
                a.acc_parent, 
                a.balance
            });
    var union = roots.Union(accounts)
        .Select(u => new
        {
            u.acc_number,
            u.acc_parent,
            u.balance
        });
    var join = union.Join(roots, u => u.acc_parent, r => r.acc_number, (a, r) => new {a, r})
        .Select(t => new
        {
            t.a.acc_number,
            t.a.acc_parent,
            root = t.r.acc_number,
            t.a.balance
        });
    var all = join.GroupBy(g => new { g.root }) // edited
                .Select(g => new
                {
                    acc_number = g.Key.root,
                    balance = g.Sum(x => x.balance ?? 0)
                })
        .ToList();
}

帐户是:

public class Account
{
    public Account()
    {
    }

    [Key]
    public string acc_number { get; set; }
    public decimal? balance { get; set; }

    public string acc_parent { get; set; }
    public virtual Account parent { get; set; }

    public virtual ICollection<Account> accounts { get; set; }
}

AccountsContext是:

public class AccountsContext : DbContext
{
    public AccountsContext() : base("localhost")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Account>()
            .HasOptional(e => e.parent)
            .WithMany(e => e.accounts)
            .HasForeignKey(e => e.acc_parent);
    }

    public DbSet<Account> Accounts { get; set; }
}

预期结果应为:

01 > 200
05 > 100
07 > 230

当我使用SQL语句时,我得到了正确的结果但是当我使用Linq表达式时,它错过了一个帐户,帐号04,因为我得到了:

01 => 100
05 => 100
07 => 230

0 个答案:

没有答案