4

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.

j0k
  • 22,600
  • 28
  • 79
  • 90
Andriy Drozdyuk
  • 58,435
  • 50
  • 171
  • 272
  • I would highly recommend you read these series: http://weblogs.asp.net/manavi/archive/2011/03/27/associations-in-ef-4-1-code-first-part-1-introduction-and-basic-concepts.aspx – Moeri Aug 09 '13 at 06:40

1 Answers1

3
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.

Roman Bats
  • 1,775
  • 3
  • 30
  • 40
  • Well, I mean you _did_ specify `HasRequired` (which is waht I had). The extra thing you added was `WithOptional` -- could you explain what that does? – Andriy Drozdyuk Aug 09 '13 at 16:07
  • 1
    It is one-to-zero or one relationship. WithOptional means that Crank can has one or zero relations with Box. http://stackoverflow.com/a/5423308/1219444 - more explanations for same situation. – Roman Bats Aug 09 '13 at 17:45