【问题标题】:Must declare the table variable "@p0"必须声明表变量“@p0”
【发布时间】:2018-06-03 19:08:15
【问题描述】:

我正在使用实体框架核心的ExecuteSqlCommand 删除表的所有行。 但是,我收到一个错误System.Data.SqlClient.SqlException: 'Must declare the table variable "@p0".'

这是我的代码:

 public static void ExecuteDeleteSQL(ShoppingCartDbContext context, string tableName)
 {
     context.Database.ExecuteSqlCommand($"Delete from {tableName}"); //This line throws the error
 }

在这里调用:

ExecuteDeleteSQL(context, "[dbo].[ShoppingCartItems]");

我正在使用 .NET Core 2 和 EntityFrameworkCore

我已经安装了以下 nuget 包:

    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />

【问题讨论】:

    标签: asp.net-core-2.0 entity-framework-core-2.1


    【解决方案1】:

    似乎您必须将至少一个参数传递给ExecuteSqlCommand,即使我的查询没有使用任何参数。 而且令人讨厌的是它在编译时不会报错。

    //passing at least one parameter    
    context.Database.ExecuteSqlCommand($"Delete from {tableName}",tableName); 
    

    编辑:

    GitHub 中报告了一个类似的问题,目前正在考虑中: https://github.com/aspnet/EntityFrameworkCore/issues/10956

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多