首页 > 解决方案 > .NET Core 使用 IdentityUser 创建不可为空的 FK 约束

问题描述

我正在尝试使用 .NET Core 2.2 中的 EF 迁移创建从我的主要 IdentityUser 到另一个类的关系。我遇到了一个问题,那就是正在使用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);
            });

我现在得到了正确的不可为空的约束,但它是重复的。(有一个 1 附加)。我的问题是:

  1. 简单地修改迁移文件并收工对我来说安全吗?
  2. 如何在我的类ApplicationUserPurchase类之间创建关系,以便生成的迁移文件给我一个不可为空的 FK 约束?

标签: c#entity-frameworkasp.net-coreasp.net-core-mvc

解决方案


1) 可以,但每次后续迁移都会重新制作此字段并导致您遇到问题。此外,由于数据类型不匹配,因此无法按预期工作

2)外键的id类型错误。应用程序用户具有类型的主键,string但您正在使用int,因此无法识别正确的外键。

更正后,将Required属性放在类上。所以最后一堂课看起来像

using System.ComponentModel.DataAnnotations;

public class Purchase
{
    public int Id { get; set; }
    // others

    [Required]
    public string ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
} 

推荐阅读