Andriy Drozdyuk
Andriy Drozdyuk

Reputation: 61041

How to model one way one-to-one in Fluent EF?

Let's say I have the following entities:

Box
  Id
  Crank crank // has one required relationship 

Crank
  Id   // does not care about the box

What is the proper way to define BoxMap? Is this sufficient? Or do I need WithRequiredPrincipal (which I have no idea what that does):

HasKey(t => t.Id);
ToTable("Boxes")
Property(t=>t.Id).HasColumnName("Id")
Property(t=>t.CrankId).HasColumnName("Crank_Id")
HasRequired(t=>t.Crank)

NOTE: Any good resources on learning fluent api are welcome. Thanks.

Upvotes: 4

Views: 1710

Answers (1)

Roman Bats
Roman Bats

Reputation: 1795

public class Context : DbContext
{
    public DbSet<Box> Boxes { get; set; }
    public DbSet<Crank> Cranks { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Box>()
            .HasRequired(m => m.Crank)
            .WithOptional()
            .Map(m => m.MapKey("Crank_Id"));

        base.OnModelCreating(modelBuilder);
    }
}

public class Box
{
    public int Id { get; set; }
    public Crank Crank { get; set; } // has one required relationship 
}

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

You don't need to specify this:

HasKey(t => t.Id);
ToTable("Boxes")
Property(t=>t.Id).HasColumnName("Id")
Property(t=>t.CrankId).HasColumnName("Crank_Id")
HasRequired(t=>t.Crank)

It will be detected by convention of EF.

Upvotes: 3

Related Questions