【问题标题】:Entity Framework: Passing String Parameter to FromSql Statement in Version 2.2实体框架:2.2 版本中将字符串参数传递给 FromSql 语句
【发布时间】:2020-10-09 02:03:36
【问题描述】:

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

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

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();

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

使用 Net Core 2.2

【问题讨论】:

  • 您需要确定要选择哪些列,并在表名前使用关键字 FROM。 SELECT something FROM table WHERE stuff
  • 你的意思是把productKey赋值为参数值吗?你有 productNumber,我看不出它是在哪里定义的。
  • 你的数据库中ProductKey的数据类型是什么?
  • 您链接到的问题的公认答案是错误的,因此您的代码也是错误的。
  • 旁注:您不需要.Select(c =&gt; c.ProductId),因为您在查询中指定了列名,并且它是您要返回的唯一列。也许'.ToList()'?

标签: c# .net entity-framework .net-core .net-core-2.2


【解决方案1】:

1) 查询不正确:您没有 FROM 语句,这是必需的。 我想你想要类似的东西

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

2) 使用 FromSQL 时:在查询字符串中,您必须输入参数的名称,而不是实例。所以把 {productParameter} 改成 @productKey

3) 将 SqlParameter 实例作为第二个参数传递给 FromSql 方法。

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

【讨论】:

  • 您的代码与您的解释不符。您没有在 sql 中使用@productKey
  • 您可以使用 @productKey 代替 {productParameter.Name}。实际上 productParameter.Name 是@productKey。您可以在调试会话期间检查它。我这里只是用productParameter.Name来避免代码重复。
  • 我知道你可以使用它,但是如果你只是要使用插值来构建 sql,那么 sql 参数的意义何在?
  • 你不明白。我并不是说你不应该使用参数。我是说你的代码在技术上没有使用一个。通过使用{productParameter.Name},您使用的是字符串插值,而不是使用传递给命令的 SqlParameter。应该是:where product.ProductKey = @productKey"。您可以将$ 放在字符串上。
【解决方案2】:

这可能会奏效:

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

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

【讨论】:

  • 您忘记将参数添加到命令中。只是将“@productKey”放在字符串中是行不通的。
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多