首页 > 解决方案 > 必须声明表变量“@p0”

问题描述

我正在使用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.0entity-framework-core-2.1

解决方案


ExecuteSqlCommand即使我的查询不使用任何参数,您似乎也必须至少传递一个参数。烦人的一点是它在编译时不会抱怨。

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

编辑:

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


推荐阅读