c# - 是否有代码可以让我在 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
解决方案
我认为您需要将其分解为两个单独的部分:
首先从数据库中获取下一个序列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}";
推荐阅读
- c# - 如何使用 Rider 发布我的 WPF 解决方案?
- android - 在 libcore.io.Linux.access(Linux.java:-1)的线程“SharedPreferencesImpl-load”中发生异常“android.system.ErrnoException”
- visual-studio-extensions - 无法下载任何 Microsoft Visual Studio 2019 扩展
- java - 有没有办法在我的 Java 代码中调用 2 个类?
- visual-studio-code - 无法运行 yacc 或 flex 命令 VS Code
- powershell - 尝试从脚本中的子文件夹获取 acl 时出错
- syntax - Terraform:如何在资源中进行数学运算
- jenkins-plugins - 使用 Kubernetes Jenkins 插件自定义代理镜像
- flutter - 在 Flutter 中从 Cloud Firestore 文档中读取多个数组
- python - Docker Compose 来自 Bitbucket 克隆存储库。本地构建错误,AppBuild 退出代码,它是什么?