Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework : Fluent API makes duplicate foreign keys in one to zero or one

Tags:

c#

entity

fluent

I have some models and I want to have a "One to zero or one" association. I searched and tried to make the association using Fluent API. Here are my classes :

public partial class Bill
{

[Key]
public int Id { get; set; }
[Required]
public double Amount { get; set; }

public virtual DomainRegOrder DomainRegOrder { get; set; }

}

public partial class DomainRegOrder
{
[Key]
public int Id { get; set; }
[Required]
public string DomainName { get; set; }

public virtual Bill Bill { get; set; }
}

and in the my DataContext class :

public class DataContext : DbContext {

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

 modelBuilder.Entity<DomainRegOrder>()
 .HasOptional(x => x.Bill)
 .WithOptionalDependent();

 }

but when I Initialize the Database, in the Bills table, I will have two columns named "DomainRegOrder_Id" and "DomainRegOrder_Id1".

I tried to add the DomainRegOrderId in the Bill entity as bellow:

public int? DomainRegOrderId { get; set; }

But there will be a "DomainRegOrderId" and a "DomainRegOrder_Id" on the "Bills" table.

I also changed .WithOptionalDependent() to .WithOptionalPrincipal() but no changes were made as far as I know!!

Would somebody help me to get rid of these duplicate foreign keys, please?

like image 215
Arman Avatar asked Dec 28 '25 20:12

Arman


1 Answers

I believe you want something like this:

modelBuilder.Entity<Bill>() 
  .HasOptional(x => x.DomainRegOrder) 
  .WithOptionalDependent(c => c.Bill).Map(p => p.MapKey("DomainRegOrderID"); 
like image 73
Erik Funkenbusch Avatar answered Dec 31 '25 10:12

Erik Funkenbusch