【发布时间】:2019-01-28 04:14:20
【问题描述】:
我正在尝试使用 .NET Core 2.2 中的 EF 迁移创建从我的主要 IdentityUser 到另一个类的关系。我遇到了一个问题,那就是正在使用 null FK 约束创建迁移。这是我不想要的。
我担心,我不应该手动编辑迁移文件(来解决这个问题),因为当我将来更改这些模型时,我的手动编辑将被覆盖(因为我的类的编码不正确)。
这些是我的课程..
public class ApplicationUser : IdentityUser
{
public List<Purchase> Purchases { get; set; }
}
public class Purchase
{
public int Id { get; set; }
// others
}
生成的迁移文件在 ApplicationUserId 上设置了 nullable: true 属性
migrationBuilder.CreateTable(
name: "Purchase",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ApplicationUserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Purchase", x => x.Id);
table.ForeignKey(
name: "FK_Purchase_AspNetUsers_ApplicationUserId",
column: x => x.ApplicationUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
不正确。因此,我在 Purchase 类中添加了属性(就像我在项目中的其他 POCO 中一样)..
public class Purchase
{
public int Id { get; set; }
// others
public int ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
并重新运行迁移重新生成..
migrationBuilder.CreateTable(
name: "Purchase",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ApplicationUserId = table.Column<int>(nullable: false),
ApplicationUserId1 = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Purchase", x => x.Id);
table.ForeignKey(
name: "FK_Purchase_AspNetUsers_ApplicationUserId1",
column: x => x.ApplicationUserId1,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
我现在得到了正确的 non-nullable 约束,但它是重复的。 (有一个 1 附加)。我的问题是:
- 简单地修改迁移文件并收工对我来说安全吗?
- 如何在
ApplicationUser和Purchase类之间创建关系,以便生成的迁移文件为我提供不可为空的 FK 约束?
【问题讨论】:
标签: c# entity-framework asp.net-core asp.net-core-mvc