I'm trying to use EF Core 3 to delete all rows from a table like:
db.MyTable.ExecuteSqlRaw("delete from MyTable;");
But I get the error:
DbSet' does not contain a definition for 'ExecuteSqlRaw' and no accessible extension method 'ExecuteSqlRaw' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)
The Microsoft breaking changes page for EF Core 3 does not offer any advice on if there are special packages required to enable this:
These are the Nuget packages I have installed:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.2" /> <PackageReference Include="System.Linq" Version="4.3.0" /> <PackageReference Include="System.Linq.Expressions" Version="4.3.0" /> <PackageReference Include="System.Linq.Queryable" Version="4.3.0" />
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore;
FromSqlRaw is available, but
ExecuteSqlRawAsync , etc are not.
EDIT: I added a
using Microsoft.EntityFrameworkCore and the error has changed to:
'DbSet' does not contain a definition for 'ExecuteSqlRaw' and the best extension method overload 'RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(DatabaseFacade, string, params object)' requires a receiver of type 'DatabaseFacade'
My edit about the new error led me to an answer:
The Microsoft Breaking Changes documentation is just not providing examples for the Execute methods. To get that to work you have to go through the "Database" property instead. So in short, to use those:
myContext.Database.ExecuteSqlRaw(@"...sql to excxute...")
I had similar issue with dbContext.Database.ExecuteSqlRaw() and it has been fixed by installing package Microsoft.EntityFrameworkCore.SqlServer without even using the package.
install-package Microsoft.EntityFrameworkCore.SqlServer in your current project.