EF Core 2.2, Passing String Parameter to FromSql Statement

entity-framework-core

Question

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')

The Job_Number field in the table is a varchar and is stored with leading spaces for any unused digits. When I run the above function with Job_Number hard-coded, the query runs as intended. However, the SQL produced by passing the same value as a parameter looks like this and the SQL run appears to pass a number rather than a string:

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)

Why is the string parameter passed into the SQL statement as 123 and not ' 123'? I'm unsure how to adjust my function so that the parameter is not passed as a number.

Revised code per accepted solution:

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();
}
1
1
3/18/2019 4:28:29 PM

Accepted Answer

Have you tried explicitly setting the SQL data type, something like:

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();
}
1
3/18/2019 10:13:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow