Search code examples
entity-frameworkforeign-keysentity-relationshipone-to-one

EF Code First and modelbuilder - how to make a one-to-one relationship with the same ID?


I have two classes:

public class Account
{
   public int Id {get;set;}

   public PayoffData PayoffData {get;set;}
}

public class PayoffData
{
   public int Id {get;set;}
   //some other fields
}

Now, i want class PayoffData to have the same id that class Account has, and it needs to be one-to-one relationship (account can (or can not) have one payoffdata).

I've tried to do something with modelbuilder, but as far i can see that to set up a foreignkey in PayoffData class, i need to set a .HasMany relationship, which i don't want. How can i solve my problem using modelbuilder? (I don't want to use data annotations approach)


Solution

  • modelBuilder.Entity<Account>()
        .HasOptional(a => a.PayoffData)
        .WithRequired();
    

    Both tables will have a primary key column called Id and the primary key Id in the PayoffData table will be the foreign key to the Account table at the same time.