简体   繁体   English

将 SQL 语句转换为 Linq 表达式

[英]Convert SQL Statement into Linq expression

I am quite new to linq and .net core.我对 linq 和 .net 内核很陌生。 I am trying to calculate the next tax return date of a company as a part of my final year's project.作为我最后一年项目的一部分,我正在尝试计算公司的下一个纳税申报日期。

  1. If there is a newly made company with no tax has been made yet (means no entry in the tax table), Then add 18 months in the company's incorporated date.如果有一个新成立的公司还没有纳税(意味着税表中没有条目),则在公司成立日期上增加18个月。
  2. If the company has already paid tax, then pick the latest date TaxReturnDate from tax table and add 9 months into that to get the next TaxReturnDate.如果公司已经缴纳了税款,则从税表中选择最晚的日期 TaxReturnDate 并添加 9 个月以获得下一个 TaxReturnDate。

Thats what i have tried in SQL, now i am trying to convert this sql into Linq Query, I need some help to get the desired results.这就是我在 SQL 中尝试过的,现在我正在尝试将此 sql 转换为 Linq 查询,我需要一些帮助才能获得所需的结果。

 WITH cte_company (CompanyID, CompanyName, CompanyNumber, IncorporatedDate, TOTAL_YEARS) AS (SELECT CompanyID, CompanyName, CompanyNumber, IncorporatedDate, DATEDIFF(YEAR, IncorporatedDate, CURRENT_TIMESTAMP) AS TOTAL_YEARS FROM tbl_Company) SELECT cte_company.CompanyID, CompanyName, CompanyNumber, IncorporatedDate, TOTAL_YEARS, CASE WHEN TOTAL_YEARS > 1 THEN (SELECT DATEADD(MONTH, 9, MAX(TaxReturnDate)) FROM tbl_Tax WHERE cte_company.CompanyID = tbl_Tax.CompanyID) ELSE DATEADD(MONTH, 18, IncorporatedDate) END AS TaxDate FROM cte_company

Linq Query Linq查询

IEnumerable<CompanyTaxInfo> result = from c in this.AcmeDB.tbl_Company let TotalYears = (DateTime.Now - c.IncorporatedDate).Value.Days / 365 let taxReturnDate = this.AcmeDB.tbl_Tax.Max(tx => tx.TaxReturnDate).Value.AddMonths(9) select new CompanyTaxInfo { CompanyID = c.CompanyID, CompanyName= c.CompanyName, CompanyNumber= c.CompanyNumber, IncorporatedDate= c.IncorporatedDate, TotalYears = TotalYears, TaxDate = TotalYears > 1? taxReturnDate: c.IncorporatedDate.Value.AddMonths(21) }; return result;

code is throwing DbArithmeticExpression arguments must have a numeric common type.'代码抛出 DbArithmeticExpression arguments must have a numeric common type。 exception.例外。

Please help请帮忙

Try the following query:尝试以下查询:

 var query = from c in this.AcmeDB.tbl_Company let TotalYears = EF.Functions.DateDiffYear(c.IncorporatedDate, DateTime.Now) select new CompanyTaxInfo { CompanyID = c.CompanyID, CompanyName = c.CompanyName, CompanyNumber = c.CompanyNumber, IncorporatedDate = c.IncorporatedDate, TotalYears = TotalYears, TaxDate = TotalYears > 1? this.AcmeDB.tbl_Tax.Where(tax => c.CompanyId == tax.CompanyId).Max(tx => tx.TaxReturnDate).Value.AddMonths(9): c.IncorporatedDate.Value.AddMonths(18) }; return query.ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM