.NET Core使用IdentityUser

时间:2019-01-28 04:14:20

标签: c# entity-framework asp.net-core asp.net-core-mvc

我正在尝试使用.NET Core 2.2中的EF迁移创建从我的主要IdentityUser到另一个类的关系。我遇到了一个问题,那就是使用 null FK约束创建迁移。这是我不想要的东西。

我担心,我不应该手动编辑迁移文件(以解决此问题),因为将来将来更改这些模型时,我的手动编辑将被覆盖(因为我的类编码不正确)。 / p>

这些是我的课程。

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约束?

1 个答案:

答案 0 :(得分:2)

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; }
} 
相关问题