简体   繁体   English

无法在没有 EF 的情况下将 ApplicationUser 设置为外键正在创建一个新表

[英]Not able to set ApplicationUser as foreign key without EF is creating a new table

Im new in ASP.NET Core and EF.我是 ASP.NET Core 和 EF 的新手。 When i try to add ApplicationUser as a foreign key, EF will create a new table "ApplicationUser" but i want to relate this field with the Identity Framework Table "ASPNetUser".当我尝试将 ApplicationUser 添加为外键时,EF 将创建一个新表“ApplicationUser”,但我想将此字段与身份框架表“ASPNetUser”相关联。

What do i wrong?我怎么了?

This is my code:这是我的代码:

    public class Posts
{
    public int Id { get; set; }
    public string Content { get; set; }
    public DateTime Created { get; set; }
    [Key]
    public int CreatorId { get; set; }

    [ForeignKey("CreatorId")]
    public ApplicationUser Creator { get; set; }
}

EF created the migration like this: EF 创建了这样的迁移:

  migrationBuilder.CreateTable(
            name: "ApplicationUser",
            columns: table => new
            {
                Id = table.Column<string>(nullable: false),
                UserName = table.Column<string>(nullable: true),
                NormalizedUserName = table.Column<string>(nullable: true),
                Email = table.Column<string>(nullable: true),
                NormalizedEmail = table.Column<string>(nullable: true),
                EmailConfirmed = table.Column<bool>(nullable: false),
                PasswordHash = table.Column<string>(nullable: true),
                SecurityStamp = table.Column<string>(nullable: true),
                ConcurrencyStamp = table.Column<string>(nullable: true),
                PhoneNumber = table.Column<string>(nullable: true),
                PhoneNumberConfirmed = table.Column<bool>(nullable: false),
                TwoFactorEnabled = table.Column<bool>(nullable: false),
                LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
                LockoutEnabled = table.Column<bool>(nullable: false),
                AccessFailedCount = table.Column<int>(nullable: false),
                FirstName = table.Column<string>(type: "nvarchar(150)", nullable: true),
                LastName = table.Column<string>(type: "nvarchar(150)", nullable: true),
                Birthdate = table.Column<DateTime>(type: "DateTime2", nullable: false),
                EntryDate = table.Column<DateTime>(type: "DateTime2", nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_ApplicationUser", x => x.Id);
            });

        migrationBuilder.CreateTable(
            name: "Posts",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Content = table.Column<string>(nullable: true),
                Created = table.Column<DateTime>(nullable: false),
                CreatorId1 = table.Column<string>(nullable: true),
                CreatorId = table.Column<int>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Posts", x => x.Id);
                table.ForeignKey(
                    name: "FK_Posts_ApplicationUser_CreatorId1",
                    column: x => x.CreatorId1,
                    principalTable: "ApplicationUser",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

        migrationBuilder.CreateIndex(
            name: "IX_Posts_CreatorId1",
            table: "Posts",
            column: "CreatorId1");

But my Users will be created in this table:但我的用户将在此表中创建:

但我的用户将在此表中创建:

It looks like you want to use the [Table("AspNetUsers")] annotation.看起来您想使用[Table("AspNetUsers")]注释。

See here: How to Specify Entity Framework Core Table Mapping?请参阅此处: 如何指定实体框架核心表映射?

Important Caveat: Since it looks like you're trying to re-use an existing table, you will need to create a migration but then modify it in order to prevent Entity Framework from trying to recreate the table .重要警告:由于您似乎正在尝试重新使用现有表,因此您需要创建一个迁移,然后对其进行修改以防止 Entity Framework 尝试重新创建该表

So i figured it out... i forgot the Releationship in the DBContext... After i added this, my Migration works as expeted and added ApplicationUser as foreign Key in my Post Model:所以我想通了......我忘记了 DBContext 中的 Releationship ......在我添加这个之后,我的迁移工作正常,并在我的 Post 模型中添加了 ApplicationUser 作为外键:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Posts>()
        .HasOne(p => p.Creator)
        .WithMany(p => p.Posts)
        .HasForeignKey(p => p.CreatorId)
        .OnDelete(DeleteBehavior.Cascade);
}

[Key] attribute is used to create primary key. [Key]属性用于创建主键。 It being assigned to Creator property caused EF to create separate column它被分配给Creator属性导致 EF 创建单独的列

public class Posts
{
    [Key]
    public int Id { get; set; }
    public string Content { get; set; }
    public DateTime Created { get; set; }
    
    [ForeignKey("Creator")]
    public int CreatorId { get; set; }

    [ForeignKey("CreatorId")]
    public ApplicationUser Creator { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 同一主键ApplicationUser表上的EF多个外键关系 - EF multiple foreign key relationship on same primary key ApplicationUser table 如何在 EF Core 中的不同项目之间向 ApplicationUser 添加外键? - How to add a foreign key to ApplicationUser between separate project in EF Core? 使用UserName作为实体框架中的外键创建ApplicationUser导航属性 - Creating an ApplicationUser navigation property using UserName as the foreign key in Entity Framework 在EF 4上映射外键而不创建新的Edmx文件 - Mapping foreign keys on EF 4 without creating a new Edmx file EF代码首先使用空查找表设置外键 - EF Code first set a foreign key with an empty lookup table 无论如何将 ApplicationUser 扩展到 ApplicationRole 的外键以获取 EF 核心中的所有数据? - is there anyway to extend ApplicationUser to foreign key to ApplicationRole to get all data in EF core? EF6 ApplicationUser错误的多个外键 - EF6 Multiple foreign keys for ApplicationUser Error 在sql表中创建新条目时EF需要主键 - EF Requiring primary key when creating a new entry in sql table 使用Entity Framework Core使用外键创建新表 - Creating new table with foreign key with Entity Framework Core 如何防止EF创建外键? - How to prevent EF from creating a foreign key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM