0

It seems that Entity Framework have some conventions to deal with one to one relationship.

I'm using Fluent API and I need my child entity to have PK and Also FK.

Is it possible without using the [ForeignKey] attribute?

Thiago Custodio
  • 17,332
  • 6
  • 45
  • 90

1 Answers1

0

Consider the following example:

public class Principal
{
    public int Id { get; set; }
    public Dependent Dependent { get; set; }
}

public class Dependent
{
    public int Id { get; set; }
    public Principal Principal { get; set; }
}

To configure Dependent's Id property to be a foreign key to Principal's Id property with Fluent API you may choose one of the following options:

1) Starting with Entity<Dependent>:

public class AppDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Dependent>().HasRequired(d => d.Principal).WithOptional(p => p.Dependent);
    }
}

2) Starting with Entity<Principal>

public class AppDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {             
        modelBuilder.Entity<Principal>().HasOptional(p => p.Dependent).WithRequired(d => d.Principal);
    }
}

They both will result in the following code first migration:

CreateTable(
    "dbo.Principals",
    c => new
        {
            Id = c.Int(nullable: false, identity: true),
        })
    .PrimaryKey(t => t.Id);

CreateTable(
    "dbo.Dependents",
    c => new
        {
            Id = c.Int(nullable: false),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.Principals", t => t.Id)
    .Index(t => t.Id);

where Dependent's Id property is configured to be as a PK and a FK to Principal's Id property.

Deilan
  • 4,740
  • 3
  • 39
  • 52