【问题标题】:Convert complex SQL query to LINQ for rest api将复杂的 SQL 查询转换为 LINQ for rest api
【发布时间】:2021-06-07 22:48:27
【问题描述】:

我有两张表,一张是账户交易,另一张是账户代码。我想获取帐户名称列表及其当前帐户余额。下面的 sql 代码对我来说很好用,但现在我要使用我需要 Linq 查询的 rest api。

请帮我将下面的 SQL 查询转换为实体框架 LINQ 查询

select 
    ac.AccountCode, 
    COALESCE(SUM(Credit), 0) - COALESCE(SUM(Debit), 0) as Balance 
from 
    tblTransaction t 
inner join 
    tblAccountCodes ac on t.accredit = ac.AccountCode 
                       or t.AcDebit = ac.AccountCode 
where 
    Transaction_Type in ('T_', 'P_', 'R_') 
    and Creatd_Date >= '1999-01-01' 
    and valid = 'valid' 
    and Creatd_Date <= '3/10/2021' 
    and branch = 'MAIN' 
    and ac.Branch = 'MAIN' 
group by 
    AccountCode ;

任何帮助将不胜感激,我需要将精确查询转换为 LINQ,因为在我的交易表中,我使用两列用于贷记和借记。

我试过了,但是说运算符'||'不能应用于'string'和'string'类型的操作数

var credibalance = from trans in aceMoneyDb.tblTransactions
                   //where t.UID == userId
                   join acs in aceMoneyDb.tblAccountCodes
                            on (trans.AcCredit || trans.AcDebit) equals acs.AccountCode
                   into alldata
                   from data in alldata.DefaultIfEmpty()
                   select new
                          {
                              
                              AccountCode = data.AccountCode == null ? "-" : data.AccountCode,
                              Balance = trans.Credit == null ? 0 : trans.Credit,
                      
                          };

【问题讨论】:

  • 所以你有一个需求,导致一些SQL代码,现在你不给我们需求,而是提供SQL代码,我们要从中提取需求。考虑编辑您的问题并添加要求:“我有事务表和事务代码表,其具有......使用外键的关系......请给我那些事务及其事务代码......键入相关部分也会有所帮助
  • @HaraldCoppoolse 我已添加要求

标签: sql entity-framework linq sql-to-linq-conversion


【解决方案1】:

此 LINQ 查询应该更接近您的 SQL。主要思想是这种内连接可以由SelectManyWhere定义:

var transactionTypes = new []{"T_", "P_", "R_"};
var startDate = new DateTime(1999, 1, 1);
var endDate = new DateTime(2021, 3, 10);

var credibalance = 
    from trans in aceMoneyDb.tblTransactions
    from acs in aceMoneyDb.tblAccountCodes
        .Where(acs => trans.AcCredit == acs.AccountCode || trans.AcDebit == acs.AccountCode)
    where transactionTypes.Contains(trans.Transaction_Type) 
        && trans.Creatd_Date >= startDate && trans.Creatd_Date <= endDate
        && trans.valid == "valid"
        && trans.branch == "MAIN"
        && acs.branch == "MAIN"
    group trans by new { acs.AccountCode } into g
    select new
    {
        AccountCode = g.Key.AccountCode ?? "-",
        Balance = ((double?)g.Sum(t => t.Credit) ?? 0) - ((double?)g.Sum(t => t.Debit) ?? 0),
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    相关资源
    最近更新 更多