I wish to run a raw SQL Delete Query on EF Core and I am suing the following guide to help me along: https://learn.microsoft.com/en-us/ef/ef6/querying/raw-sql
The code:
using (accountingContext db = new())
{
db.Database.ExecuteSqlCommand("DELETE FROM ...");
}
but I get the error:
DatabaseFacade does not contain a definition for 'ExecuteSqlCommand'
my accountingContext class:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WebApi.Models
{
public partial class accountingContext : DbContext
{
public DbSet<User>? Users { get; set; }
public DbSet<Transaction>? Transactions { get; set; }
public DbSet<TransactionStaging>? TransactionsStaging { get; set; }
public accountingContext()
{
}
public accountingContext(DbContextOptions<accountingContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("****");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
}
the .csproj file:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="28.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Resources\Temp\" />
</ItemGroup>
</Project>
What am I doing wrong here?
The following resolved the issue for me:
db.Database.ExecuteSqlRaw("...");
Not sure why all the docs I was going through were suggesting the use of ExecuteSqlCommand but eventually I stumbled on the correct command.
For EF Cor you need to use the ExecuteSqlRaw or ExecuteSql commands included in the Extensions Nuget package Microsoft.EntityFrameworkCore.Relational
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With