我希望在 EF Core 上运行原始 SQL 删除查询,并且我正在起诉以下指南来帮助我: https://learn.microsoft.com/en-us/ef/ef6/querying/raw-sql
代码:
using (accountingContext db = new())
{
db.Database.ExecuteSqlCommand("DELETE FROM ...");
}
但我收到错误:
DatabaseFacade 不包含“ExecuteSqlCommand”的定义
我的accountingContext类:
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)
{
}
}
}
.csproj 文件:
<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>
我在这里做错了什么?
以下内容为我解决了问题:
db.Database.ExecuteSqlRaw("...");
不确定为什么我正在阅读的所有文档都建议使用 ExecuteSqlCommand,但最终我偶然发现了正确的命令。
对于 EF Cor,您需要使用扩展 Nuget 包中包含的 ExecuteSqlRaw 或 ExecuteSql 命令 Microsoft.EntityFrameworkCore.Relational
使用 Microsoft.EntityFrameworkCore.SqlServer