I am using .NET Core 6 with Entity Framework
I have 2 Models called “Category” and “Subcategory”
“Category” implements my “ICategory” interface:
public interface ICategory
{
public int Id { get; set; }
public string Label { get; set; }
public string Value { get; set; }
}
public class Category : ICategory
{
public int Id { get; set; }
public string Label { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
}
“Subcategory” inherits from “Category” and implements my “ISubcategory” interface:
public interface ISubcategory : ICategory
{
public string InputType { get; set; }
}
public class SubCategory : Category, ISubcategory
{
public string InputType { get; set; } = string.Empty;
public int CategoryId { get; set; }
}
My DataContext file looks like this:
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Category> Categories { get; set; }
public DbSet<SubCategory> SubCategories { get; set; }
}
When I run dotnet ef migrations add Migration1
it only generates a table based on the base model, “Category”:
public partial class Migration1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Label = table.Column<string>(type: "nvarchar(max)", nullable: false),
Value = table.Column<string>(type: "nvarchar(max)", nullable: false),
Discriminator = table.Column<string>(type: "nvarchar(max)", nullable: false),
InputType = table.Column<string>(type: "nvarchar(max)", nullable: true),
CategoryId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Categories");
}
}
I’m expecting the “SubCategory” table to also be generated. And I noticed that the “InputType” and “CategoryId” Properties were on the generated table even though those properties only belong to the “Subcategory” model.
As a test, I created an unrelated model that doesn’t inherit from “Category”. That table did get generated successfully in the migration. This tells me that my issue is probably related to inheritance. but I’m just not sure what the issue is. Any help is appreciated.
mg123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
By default Entity Framework generates table per hierarchy. Note, it has Discriminator
column that will hold what actual class it corresponds to. You can generate Table per type, but it is not default.
Read more in the docs: https://learn.microsoft.com/en-us/ef/core/modeling/inheritance