【问题标题】:Why is Entity Framework generating an invalid DbContext class in my .NET Core class library?为什么 Entity Framework 在我的 .NET Core 类库中生成无效的 DbContext 类?
【发布时间】:2021-05-28 13:47:24
【问题描述】:

我正在尝试在一个空的 .NET 5 库中设置 Entity Framework Core。

<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) 来生成我的模型和带有 this command 的 DbContext:

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,但没有任何改变。

这里到底发生了什么?

【问题讨论】:

    标签: c# .net-core entity-framework-core mysql-connector


    【解决方案1】:

    不要给你的班级打电话DbContext。您不能拥有与基类同名的类。更好的名字是TechTestDbContext

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

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2019-03-10
      • 2018-11-25
      • 2019-02-12
      相关资源
      最近更新 更多