如何在Fluent EF中一对一地建模?

时间:2013-08-08 19:24:13

标签: entity-framework fluent-entity-framework

假设我有以下实体:

Box
  Id
  Crank crank // has one required relationship 

Crank
  Id   // does not care about the box

定义BoxMap的正确方法是什么?这够了吗?或者我需要WithRequiredPrincipal(我不知道那是什么):

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

注意:欢迎学习流利api的任何好资源。感谢。

1 个答案:

答案 0 :(得分: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; }
}

您无需指定:

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

将通过EF的惯例检测。