首页 > 解决方案 > 是否有代码可以让我在 linq 中获取以下 sql 查询的结果?

问题描述

我正在尝试执行以下 sql 查询并将结果存储在使用 linq 的变量中,但我找不到方法吗?

该查询在 sql server 上运行良好,但是当我尝试使用 linq 执行此操作时,它并没有给我预期的结果,

查询如下,

SELECT ('PN'+CONVERT(VARCHAR(5),LenderId)+RIGHT('00000000'+CONVERT(VARCHAR(9),NextSecuenceId+1,0),(9)))
 FROM LenderSequences WHERE LenderId = '30' AND TypeDocumentId = '1'

这是我到现在为止的 linq 代码

from LenderSequences in db.LenderSequences
select new {
  Column1 = ("PN" + SqlFunctions.StringConvert((Double)LenderSequences.LenderId) + ("00000000" + SqlFunctions.StringConvert((Double)LenderSequences.NextSecuenceId + 1)).Substring(("00000000" + SqlFunctions.StringConvert((Double)LenderSequences.NextSecuenceId + 1)).Length-9,9))
}

这是我希望你回来的结果

PN30000000001

标签: c#linq

解决方案


我认为您需要将其分解为两个单独的部分:

首先从数据库中获取下一个序列ID:

SELECT NextSecuenceId
FROM LenderSequences
WHERE LenderId = '30' AND TypeDocumentId = '1'

您可以根据需要从数据库中获取此值,或者使用 ADO.NET 直接执行 SQL,或者使用像实体框架这样的 ORM。

下一步是格式化它:

// Would already have this value, or could also get it from the database
var lenderId = 3;

// This value would come from your database, as above
var nextSeqId = nextSecuenceId;

// Add the zero padding as necessary
// Assuming you want the total length to be 10 digits
var tmp = lenderId.ToString().PadRight(10 - nextSeqId.ToString().Length, '0');

// Combine all the values to create the required format
var formattedValue = $"PN{tmp}{nextSeqId}";

推荐阅读