Skip to content

Multiple one-to-one relations create duplicate foreign key field. #5344

@KorucuTech

Description

@KorucuTech

Have 2 entities


public class Customer {
  public int Id {get; set;}
  public string Name {get; set;}
  public int? ShipToAddressId {get; set;}
  public int? BillToAddressId {get;set;}
  public virtual CustomerAddress ShipToAddress {get;set;}
  public virtual CustomerAddress BillToAddress {get;set}
  public virtual ICollection<CustomerAddress> CustomerAddresses {get;set;} 
}

public class CustomerAddress {
  public int Id {get;set;}
  public int CustomerId {get;set;}
  public string Name {get;set;}
  public string Address {get;set;}
  public virtual Customer Customer {get;set'}
}

with the following Fluent API in DbContext OnModelCreating method

        var customeraddress = builder.Entity<CustomerAddress>();
        customeraddress.HasKey(t => t.Id);
        customeraddress.Property(t => t.Id).ValueGeneratedOnAdd();
        customeraddress.Property(t => t.Name).IsRequired();
        customeraddress.Property(t => t.Address).IsRequired();

        var customer = builder.Entity<Customer>();
        customer.HasKey(t => t.Id);
        customer.Property(t => t.Id).ValueGeneratedOnAdd();
        customer.Property(t => t.Name).IsRequired();
        customer.HasOne(t => t.BillToAddress)
                .WithOne(c => c.Customer)
                .HasForeignKey<Customer>(f => f.BillToAddressId);
        customer.HasOne(t => t.ShipToAddress)
                .WithOne(c => c.Customer)
                .HasForeignKey<Customer>(f => f.ShipToAddressId);   

this generates an extra field called "BillToAddressId1" in Customers Table instead of using already existing "BillToAddressId" field.
So Customers table gets created with both fields.

thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions