为什么实体框架不会在迁移中生成子表?



我正在使用。net Core 6与实体框架。我有两个模型类,分别叫CategorySubcategory

Category实现了ICategory接口:

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继承自Category并实现了我的ISubcategory接口:

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

我的DbContext是这样的:

public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Category> Categories { get; set; }
public DbSet<SubCategory> SubCategories { get; set; }
}

运行

dotnet ef migrations add Migration1

它只生成基于基本模型的表,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");
}
}

我期望SubCategory表也被生成。我注意到InputTypeCategoryId属性在生成的表上,尽管这些属性只属于Subcategory模型。

作为测试,我创建了一个不从Category继承的无关模型。这个表确实在迁移中成功生成了。

这告诉我我的问题可能与继承有关。但我不知道问题出在哪里。如有任何帮助,不胜感激。

默认情况下,实体框架按层次结构生成表。注意,它有Discriminator列,它将保存它所对应的实际类。您可以为每个类型生成Table,但这不是默认值。

在文档中阅读更多内容:https://learn.microsoft.com/en-us/ef/core/modeling/inheritance

最新更新