【问题标题】:Add Foreign Key Column In EF Core在 EF Core 中添加外键列
【发布时间】:2017-12-15 01:43:05
【问题描述】:

我有一个现有的表Projects,我想向其中添加一个UserId 列,其中UserId 是一个外键。 Projects 现在有一个名称列表,但我希望每个用户管理她自己的项目。最初我可以接受“孤儿”,因为列表足够小,我可以手动清理它们。

我已经更新了我的模型以包含UserId 和导航属性User(可能不相关,但Entity 这里是IdDateModified 的基类)

public class Project : Entity
{
    public string Name { get; set; }
    public Guid? UserId { get; set; } //tried this as nullable and non nullable
    public User User { get; set; }
}

而我的相关映射文件是

public class ProjectMap : IEntityTypeConfiguration<Project>
{
    public void Configure(EntityTypeBuilder<Project> builder)
    {
        builder.Property(x => x.Name).IsRequired();
        builder.Property(x => x.UserId).IsRequired();

        builder.HasOne(x => x.User)
            .WithMany(x => x.Projects)
            .HasForeignKey(x => x.UserId)
            .OnDelete(DeleteBehavior.SetNull);  //I have tried numerous combinations of things here....
    }
}

我还为项目的User 实体添加了一个导航属性,但没有对映射类进行任何更改。

public class User : Entity
{
    public string EmailAddress { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Task> Tasks { get; set; }
    public List<Project> Projects { get; set; }
}

由此产生的迁移:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<Guid>(
            name: "UserId",
            table: "Projects",
            nullable: false,
            defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));

        migrationBuilder.CreateIndex(
            name: "IX_Projects_UserId",
            table: "Projects",
            column: "UserId");

        migrationBuilder.AddForeignKey(
            name: "FK_Projects_Users_UserId",
            table: "Projects",
            column: "UserId",
            principalTable: "Users",
            principalColumn: "Id",
            onDelete: ReferentialAction.SetNull);
    }

在运行 update-database 时转换为这条 SQL

ALTER TABLE [Projects] ADD CONSTRAINT [FK_Projects_Users_UserId] FOREIGN KEY ([UserId]) REFERENCES [Users] ([Id]) ON DELETE SET NULL;

并因此错误而失败

Cannot create the foreign key "FK_Projects_Users_UserId" with the SET NULL referential action, because one or more referencing columns are not nullable.

我做错了什么?

【问题讨论】:

  • @HaraldCoppoolse 就是这样。非常感谢你..我不敢相信我错过了。你编码不累!您能否将其添加为答案,以便我将其标记为已回答?

标签: entity-framework entity-framework-migrations ef-core-2.0


【解决方案1】:

下面的行导致了问题,因为您希望在Project 上有一个可为空的 FK

builder.Property(x => x.UserId).IsRequired();

此外,您生成的迁移已经有提示:

 nullable: false,

只需删除 Configure 方法中的那一行,它应该可以工作。您可能还需要通过运行 Remove-Migration 来删除迁移,然后再次运行 add-migration。这次你应该有这个:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AlterColumn<string>(
        name: "Name",
        table: "Projects",
        nullable: false,
        oldClrType: typeof(string),
        oldNullable: true);

    migrationBuilder.AddColumn<Guid>(
        name: "UserId",
        table: "Projects",
        nullable: true);

    migrationBuilder.CreateIndex(
        name: "IX_Projects_UserId",
        table: "Projects",
        column: "UserId");

    migrationBuilder.AddForeignKey(
        name: "FK_Projects_Users_UserId",
        table: "Projects",
        column: "UserId",
        principalTable: "Users",
        principalColumn: "Id",
        onDelete: ReferentialAction.SetNull);
}

如果您愿意,可以在配置关系时通过显式设置 IsRequired 来更具体:

private static void ConfigureProject(EntityTypeBuilder<Project> b)
{
    b.Property(x => x.Name).IsRequired();

    b.HasOne(x => x.User)
        .WithMany(x => x.Projects)
        .HasForeignKey(x => x.UserId)
        .IsRequired(false)
        .OnDelete(DeleteBehavior.SetNull);
}

我喜欢这个,即使该属性已经可以为空并且 EF 将使用它的约定来正确创建它,但对于阅读配置并了解它而无需转到实际的 Project 类的人来说仍然很好。

【讨论】:

    【解决方案2】:

    在函数配置中你指定:

    builder.Property(x => x.UserId).IsRequired();
    

    这不是说 UserId 不能为空吗?然而你希望它为空?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多