Closed ZzZombo closed 17 hours ago
@ZzZombo what's your exact expectation here with open generic entity types? For example, what should actually get created in the database table here?
Each closed generic entity type, like BaseEntity<string>
, add an entity to the TPH hierarchy in the model with BaseEntity<>
as the base type of them.
But that's not what your model configuration is doing:
_ = modelBuilder.Entity(typeof(BaseEntity<>), static (builder) => { });
Here you're asking EF to map an open generic type as an entity type, which I don't think makes sense. Try configuring entity types for the closed subtypes.
Did you not read that it doesn't work and crashes? Rendering any subsequent model configuration moot. So it was omitted from the provided code.
Yes, I read that it doesn't work and crashes - but I think you're misunderstanding what I'm trying to say; so here's a code sample which works:
await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
public class BlogContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// _ = modelBuilder.Entity(typeof(BaseEntity<>), static (builder) => { });
modelBuilder.Entity<BaseEntity<string>>();
modelBuilder.Entity<BaseEntity<int>>();
}
}
public class BaseEntity<T>
{
[Key]
public int Id { get; set; }
public T? Foo { get; set; }
}
Note that there's no configuring of the open generic base type as an entity type, since I'm not sure what that would mean. Is the above code not sufficient for you in some way?
I suppose that would work.
File a bug
Open generic types do not appear to be processed correctly. Attempting to check the model for changes/add a new migration ends with an error.
Include your code
It crashes even with you call
.Entity()
with only the type argument, the lambda is just to simulate closer our actual code.Include stack traces
Include verbose output
Include provider and version information
EF Core version: 8.0.11 Database provider: (e.g. Npgsql.EntityFrameworkCore.PostgreSQL) Target framework: (e.g. .NET 8.0-windows) Operating system: Microsoft Windows [Version 10.0.19045.5011] IDE: (e.g. Visual Studio 2022 17.11.5)