Illep
Illep

Reputation: 16849

Two Foreign Keys generated with EF

I get 2 foreign keys begin generated. How can I solve this? My code is as follows:

Note: the association with Person and User is 1-to-1-or-0. A User may or may not have a 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; }
}

Entity configuration:

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);
    }
}

Result:

I am copying part of the snippet from the migration code. As you can see, there are 2 foreign keys created, UserId and UserId1

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);
            });

Upvotes: 0

Views: 433

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89396

I overlooked the additional navigation property User.Person that isn't properly configured. This

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

should be

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

If you don't tell EF that User.Person is the inverse navigation property of Person.User it will configure two relationships.

Upvotes: 3

Related Questions