How to simulate one path to one in Fluent EF?

Let's say I have the following objects:

Box Id Crank crank // has one required relationship Crank Id // does not care about the box 

What is the correct way to determine BoxMap? is that enough? Or do I need WithRequiredPrincipal (I do not know what it 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 for learning fluent api are welcome. Thanks.

+4
source share
1 answer
 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 do not need to specify the following:

 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 discovered by agreement of the EF.

+3
source

Source: https://habr.com/ru/post/1496025/


All Articles