实体框架:在 2.2 版中将字符串参数传递给 FromSql 语句

3 .net c# entity-framework .net-core .net-core-2.2

我正在尝试将字符串参数传递给 SQL 查询,在下面接收错误。我该如何解决这个问题?当前使用答案EF Core 2.2,将字符串参数传递给 FromSql 语句

输入字符串的格式不正确。

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();
Run Code Online (Sandbox Code Playgroud)

它是来自 ProductKey 的类型 varchar(6)

使用网络核心 2.2

Cro*_*der 5

如果您正在使用,FromSql您应该像这样构造您的代码以正确应用 SqlParameter:

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

根据您使用的 EF 版本,您还可以使用SqlParameterFromSqlInterpolated代替FromSql并取消 SqlParameter。