Entity Framework Core 3 raw SQL missing methods

.net-core c# ef-core-3.0 entity-framework entity-framework-core

Question

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:

https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#fromsql-executesql-and-executesqlasync-have-been-renamed

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 statements:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;

Note that FromSqlRaw is available, but ExecuteSqlRaw, 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'

1
3
10/12/2019 6:22:15 AM

Accepted Answer

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:

  1. Make sure you have using Microsoft.EntityFrameworkCore;
  2. If using an execute use myContext.Database.ExecuteSqlRaw(@"...sql to excxute...")
0
10/11/2019 7:53:25 PM

Popular Answer

I had similar issue with dbContext.Database.ExecuteSqlRaw() and it has been fixed by installing package Microsoft.EntityFrameworkCore.SqlServer without even using the package.

try install-package Microsoft.EntityFrameworkCore.SqlServer in your current project.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow