Duplicate navigation properties when using Entity Framework 6 and fluent api


Question

I got two models with a relations.

public class Customer
{
    public Customer()
    {
        CustomerSites = new List<CustomerSite>();
    }     

    public IList<CustomerSite> CustomerSites { get; set; }
}

public class CustomerSite
{
    public Guid CustomerId { get; set; }
    public Customer Customer { get; set; }
}

The relations is built up by fluent api: (I have tried also with only one of the statement below)

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<CustomerSite>()
            .HasRequired(x => x.Customer)
            .WithMany(x => x.CustomerSites)
            .HasForeignKey(x => x.CustomerId);

        modelBuilder.Entity<Customer>()
            .HasMany(x => x.CustomerSites)
            .WithRequired(x => x.Customer)
            .HasForeignKey(x => x.CustomerId);
}

My question is why this code generates double foreign keys to the database like example below.

 "dbo.CustomerSites",
            c => new
                {                     
                    CustomerId = c.Guid(nullable: false),                     
                    Customer_Id = c.Guid(),
                })
            .ForeignKey("dbo.Customers", t => t.CustomerId, cascadeDelete: true)
            .ForeignKey("dbo.Customers", t => t.Customer_Id)

It should only be one CustomerId and not Customer_Id. As you see this is also nullable. If I remove this column in the db context is throwing exception on update. I think this is quite weird....

Popular Answer

The reason was that during re-factoring some old properties were left in the entity that influenced during auto-mapping on additional FKs in the DB.

Example: if we have

public class CustomerSite
{
    public Guid CustomerId { get; set; }
    public Customer Customer { get; set; }
    ............
    public Customer Customer1 { get; set; }
}

and have only one fluent mapping statement like

modelBuilder.Entity<CustomerSite>().HasRequired(x => x.Customer)
.WithMany(x => x.CustomerSites).HasForeignKey(x => x.CustomerId);

in the database we will have additionak FK like Customer1_Id which will be nullable.

Be attentive. May be it helps someone!!!





Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why