简体   繁体   中英

Entity Framework: Passing String Parameter to FromSql Statement in Version 2.2

I am trying to pass a string parameter to a SQL Query, Receiving error below. How can I resolve this? Currently utilizing answer EF Core 2.2, Passing String Parameter to FromSql Statement

Input String was not in a correct format.

public async Task<IEnumerable<Product>> GetProduct(string productKey)
{
    var productParameter = new SqlParameter("@productKey", SqlDbType.VarChar);
    productParameter.Value = productKey;

    var productIdList = db.TestDb
        .FromSql($"select ProductId from dbo.Product product" +
            "   (where product.ProductKey = {productParameter})" )
            .Select(c => c.ProductId).ToList();

It is type varchar(6) from ProductKey

Using Net Core 2.2

If you are using FromSql you should construct your code like this to properly apply the SqlParameter:

var productIdList = db.TestDb
    .FromSql($"select ProductId from dbo.Product product where product.ProductKey = @productKey",productParameter )
    .Select(c => c.ProductId).ToList();

Depending on the version of EF you are using, you could also use FromSqlInterpolated instead of FromSql and do away with the SqlParameter altoghter.

1) Query is not correct: you don't have FROM statement, which is required. I presume that you wanted something like

select productKey 
from dbo.Product product 
where product.Product = <paramName>

2) When using FromSQL: in the query string you have to input the name of the parameter, not the instance. So change {productParameter} to @productKey

3) Pass the SqlParameter instance as second argument to FromSql method.

var productParameter = new SqlParameter("@productKey", SqlDbType.VarChar);
productParameter.Value = productNumber;     

var product= db.Tra
    .FromSql($@"
        select productKey 
        from dbo.Product product 
        where product.ProductKey = {productParameter.Name}", productParameter);

This might do the trick:

var productParameter = new SqlParameter("@productKey", productKey);

var productIdList = db.TestDb
    .FromSql("select ProductId from dbo.Product where ProductKey = @productParameter",productParameter )
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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