【发布时间】:2020-10-19 11:58:27
【问题描述】:
我的项目中有两个DbContext,AppDbContext 和MyNewApplicationDbContext。
我在具有表Keyword 的多个项目中使用AppDbContext
public class AppDbContext : DbContext
{
public virtual DbSet<Keyword> Keywords { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.HasDefaultSchema("Common");
}
}
public class Keyword
{
public int Id { get; set; }
public string Value { get; set; }
public int ParentId { get; set; }
[ForeignKey("ParentId")]
public Keyword Parent { get; set; }
public virtual ICollection<Keyword> Keywords { get; set; }
}
现在在我的新应用程序中,我需要在 MyNewApplicationDbContext 中创建表 PoemKeyword,如下所示,并使用 Keyword 表的外键(即在 AppDbContext 中)
public class MyNewApplicationDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.HasDefaultSchema("MyNewApplicationDbSchema");
builder.Entity<PoemKeyword>()
.HasKey(e => new { e.KeywordId, e.PoemId, e.PoetId });
}
public DbSet<PoemKeyword> PoemKeywords { get; set; }
}
public class PoemKeyword
{
public int PoemId { get; set; }
public int PoetId { get; set; }
public int KeywordId { get; set; }
[ForeignKey("PoemId")]
public virtual Poem Poem { get; set; }
[ForeignKey("KeywordId")]
public virtual Keyword Keyword { get; set; }
[ForeignKey("PoetId")]
public virtual Poet Poet { get; set; }
}
然后我添加了迁移但在新的迁移中它想创建新的Keyword 表但该表已经被AppDbContext 添加了
migrationBuilder.CreateTable(
name: "Keyword",
schema: "MyNewApplicationDbSchema",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Value = table.Column<string>(nullable: false),
ParentId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Keyword", x => x.Id);
table.ForeignKey(
name: "FK_Keyword_Keyword_ParentId",
column: x => x.ParentId,
principalSchema: "MyNewApplicationDbSchema",
principalTable: "Keyword",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
注意:MyNewApplicationDbContext和AppDbContext是二合一数据库
我的数据库中现在有 Common.Keyword 表,为什么 EF 也想创建 MyNewApplicationDbSchema.Keyword 表?
编辑
我最近更改了两个不同的DbContext 的架构名称,但问题还没有解决
builder.HasDefaultSchema("SameSchemaNameInAllDbContext");
【问题讨论】:
-
1 个数据库 + 多个 DbContexts + 迁移 == 问题。当 generationg 迁移时,EF Core 不知道目标数据库状态是什么。迁移是根据当前模型和上一个模型快照之间的差异生成的 - 两者都存储在迁移项目中。
-
@IvanStoev 两个 DbContext 都在一个迁移项目中
-
@IvanStoev 我从
PoemKeyword实体中删除了public virtual Keyword Keyword { get; set; }现在EF 不添加关键字表。那么你知道是什么问题吗?
标签: c# asp.net-core entity-framework-core entity-framework-migrations