为什么 Entity Framework 在我的 .NET Core class 库中生成无效的 DbContext class?

Why is Entity Framework generating an invalid DbContext class in my .NET Core class library?

我正在尝试在一个空的 .NET 5 库中获取 Entity Framework 核心设置。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.3.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>
</Project>

我有 运行 EF 脚手架工具 (5.0.3) 来生成我的模型和 DbContext this command:

dotnet ef dbcontext scaffold 'server=localhost;database=techtest;user=root' MySql.EntityFrameworkCore -o Model -c DbContext

成功连接到MySql数据库并生成模型;但是,创建的 DbContext 有几个错误,我不确定是什么原因造成的。我根本没有更改代码。

DbContext.cs(26,26): Error CS0146: Circular base type dependency involving 'DbContext' and 'DbContext' (CS0146) (TechTest.Common)
DbContext.cs(33,33): Error CS0115: 'DbContext.OnConfiguring(DbContextOptionsBuilder)': no suitable method found to override (CS0115) (TechTest.Common)
DbContext.cs(33,33): Error CS0115: 'DbContext.OnModelCreating(ModelBuilder)': no suitable method found to override (CS0115) (TechTest.Common)
DbContext.cs(54,54): Error CS0311: The type 'TechTest.Common.Model.DbContext' cannot be used as type parameter 'TContext' in the generic type or method 'DbContextOptions<TContext>'. There is no implicit reference conversion from 'TechTest.Common.Model.DbContext' to 'Microsoft.EntityFrameworkCore.DbContext'. (CS0311) (TechTest.Common)

尝试使用不同版本的工具和包,包括Pomelo,但没有任何改变。

这里到底发生了什么?

不要打电话给你的 class DbContext。您不能拥有与基 class 同名的 class。更好的名称是 TechTestDbContext:

dotnet ef dbcontext scaffold 'server=localhost;database=techtest;user=root' MySql.EntityFrameworkCore -o Model -c TechTestDbContext