Turkeyplague
Turkeyplague

Reputation: 89

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

I'm trying to get Entity Framework Core setup inside an empty .NET 5 library.

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

I've run the EF scaffolding tool (5.0.3) to generate my models and the DbContext with this command:

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

It successfully connects to the MySql database and generates the models; however, the DbContext that is created has several errors and I'm not sure what's causing them. I haven't altered the code at all.

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)

Tried using different versions of the tools and packages, including Pomelo but it doesn't change anything.

What is actually happening here?

Upvotes: 1

Views: 206

Answers (1)

ekke
ekke

Reputation: 1400

Don't call your class DbContext. You can't have a class with the same name as the base class. A better name would be TechTestDbContext:

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

Upvotes: 2

Related Questions