New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to separate entity's primary key from base class? #27421
Comments
This is likely happening because you're mapping both Manager and ManagerEntity in your model, which means you're configuring inheritance mapping (i.e. EF thinks you intend to store both Manager and ManagerEntity instances in the database). With inheritance mapping, the key must be specified at the root. However, it seems like you only want the class separation on the .NET side, without needing any actual hierarchy, so make sure you are not mapping the base class (Manager in the above). See the minimal code sample below. Code sampleawait using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
public class BlogContext : DbContext
{
// Uncomment the below to make the exception appear
// public DbSet<Manager> Managers { get; set; }
public DbSet<ManagerEntity> ManagerEntities { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ManagerEntity>().HasKey(b => b.Id);
}
}
public class Manager
{
public string Name { get; set; }
}
public class ManagerEntity : Manager
{
public int Id { get; set; }
} However... if the goal is simply not to expose an Id property on Manager, there are simpler ways to do that rather than introducing a .NET hierarchy. You can have a private |
Now I understand EFCore mapping convention, which seems to me a magic, and I see what should I do next and other options that I can think about. Thanks, @roji. |
To make sure that the base type is not picked up by EF Core call |
Ask a question
I want to accomplish clean architecture with EF Core. I trid to separate primary key from base class, but it failed with below exception.
Include your code
Core
Infrastructure
Configure
Manager
Configure
Printer
Web API
Include stack traces
Include verbose output
Include provider and version information
EF Core version: 6.0.1
Database provider: Microsoft.EntityFrameworkCore.InMemory
Target framework: .NET 6
Operating system: Windows 10 (19044.1466)
IDE: Visual Studio 2022 17.0.4
Extra
Should I architect it by using interface, not inheritance?
At Core,
At Infrastructure,
Github source code
The text was updated successfully, but these errors were encountered: