public List<JC_PHASE_MASTER_TOTAL1_MC> GetAllByCompanyCodeJobNumber()
{
return _context.JC_PHASE_MASTER_TOTAL1_MC.FromSql(
$"SELECT * FROM JC_PHASE_MASTER_TOTAL1_MC WHERE (Job_Number = ' 123')"
).ToList();
}
Corresponding SQL:
SELECT *
FROM JC_PHASE_MASTER_TOTAL1_MC
WHERE
(Job_Number = ' 123')
表中的Job_Number字段是一个varchar,并使用前导空格存储任何未使用的数字。当我使用硬编码的Job_Number运行上述函数时,查询将按预期运行。但是,通过传递与参数相同的值而生成的SQL看起来像这样,并且SQL运行似乎传递数字而不是字符串:
public List<JC_PHASE_MASTER_TOTAL1_MC> GetAllByCompanyCodeJobNumber(string jobNumber)
{
return _context.JC_PHASE_MASTER_TOTAL1_MC.FromSql(
$"SELECT * FROM JC_PHASE_MASTER_TOTAL1_MC WHERE (Job_Number = {jobNumber})"
).ToList();
}
Corresponding SQL with ' 123' passed to the jobNumber string parameter:
SELECT *
FROM JC_PHASE_MASTER_TOTAL1_MC
WHERE
(Job_Number = 123)
为什么将字符串参数作为123而不是'123'传递给SQL语句?我不确定如何调整我的功能,以使参数不会作为数字传递。
每个接受的解决方案的修订代码:
public List<JC_PHASE_MASTER_TOTAL1_MC>GetAllByCompanyCodeJobNumber(string jobNumber)
{
var jobNumberParameter = new SqlParameter("@jobNumber", SqlDbType.VarChar);
jobNumberParameter.Value = jobNumber;
return _context.JC_PHASE_MASTER_TOTAL1_MC.FromSql(
$"SELECT * FROM JC_PHASE_MASTER_TOTAL1_MC WHERE (Job_Number = {jobNumberParameter})"
).ToList();
}
答案 0 :(得分:1)
您是否尝试过显式设置SQL数据类型,例如:
public List<JC_PHASE_MASTER_TOTAL1_MC>GetAllByCompanyCodeJobNumber(string jobNumber)
{
var jobNumberParameter = new SqlParameter("@jobNumber", SqlDbType.VarChar);
jobNumberParameter.Value = jobNumber;
return _context.JC_PHASE_MASTER_TOTAL1_MC.FromSql(
$"SELECT * FROM JC_PHASE_MASTER_TOTAL1_MC WHERE (Job_Number = {jobNumberParameter})"
).ToList();
}