【问题标题】:Two Foreign Keys generated with EF使用 EF 生成的两个外键
【发布时间】:2020-12-03 20:57:29
【问题描述】:

我开始生成 2 个外键。我该如何解决这个问题?我的代码如下:

注意:与 PersonUser 的关联是 1-to-1-or-0。 User 可能有也可能没有Person

public class User : Entity
{
    public string Name { get; set; }
    public Person Person { get; set; }
}

public class Person: Entity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public User User { get; set; }
    public ICollection<PersonSchool> PersonSchool{ get; set; }
}

实体配置:

public class UserEntityConfiguration : IEntityTypeConfiguration<User>
{ 
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.ToTable("User");
        builder.HasKey(c => c.Id);
        builder.Property(c => c.Name).IsRequired(true);
    }
}

public class PersonEntityConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> builder)
    {
        builder.ToTable("Person");
        builder.HasKey(c => c.Id);
        builder.Property(c => c.FirstName).IsRequired(true);
        builder.Property(c => c.LastName).IsRequired(true);
        builder.HasOne(i => i.User)
           .WithOne()
           .HasForeignKey<Person>(rl => rl.UserId)
           .OnDelete(DeleteBehavior.Restrict);
    }
}

结果:

我正在从迁移代码中复制部分 sn-p。如您所见,创建了 2 个外键,UserIdUserId1

constraints: table =>
            {
                table.PrimaryKey("PK_Person", x => x.Id);
                table.ForeignKey(
                    name: "FK_Person_User_UserId",
                    column: x => x.UserId,
                    principalTable: "User",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
                table.ForeignKey(
                    name: "FK_Person_User_UserId1",
                    column: x => x.UserId1,
                    principalTable: "User",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

【问题讨论】:

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


    【解决方案1】:

    我忽略了未正确配置的附加导航属性 User.Person。这个

    builder.HasOne(i => i.User)
       .WithOne()
       .HasForeignKey<Person>(rl => rl.UserId)
       .OnDelete(DeleteBehavior.Restrict);
    

    应该是

    builder.HasOne(i => i.User)
       .WithOne(u => u.Person)
       .HasForeignKey<Person>(rl => rl.UserId)
       .OnDelete(DeleteBehavior.Restrict);
    

    如果您不告诉 EF User.Person 是 Person.User 的反向导航属性,它将配置两个关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2015-08-08
      • 1970-01-01
      • 2020-06-05
      • 2019-06-22
      • 2021-05-23
      相关资源
      最近更新 更多