EF 零到一 FLUENT API 非键上的外键

EF zero-to-one FLUENT API Foreign Key on a NON Key

我有一个遗留数据库,它违反了 Codd 的所有规则。这是实体

class Item {
      [Key]         
      public int ItemId {get;set;}

      public string ItemNo {get;set; }

      [ForeignKey("ItemId")]
      public virtual NumericItem {get;set;} //navigation

}


class NumericItem {  //This is a subset of the Item entity

      [ForeignKey("ItemId")]
      public Item Item {get; set;}

      [Key]         
      public int ItemNo { get; set; } //this is a primary key, different type

      public int ItemId { get; set; } //this is also a primary key  and a foreign key

}

我如何首先使用 Fluent API 告诉 EF Code NumericItem 始终有一个 Item,而 Item 可能有也可能没有 NumericItem。基数总是 zero/one

这是外键的情况。

通常,当你有一个主体实体(如Item)和一个可选的依赖(NumericItem)在0或1的关系中时,依赖主键也是外键校长。在您的情况下,由于数据库已经是那样,您可以这样做:

public class Item
{
    public int ItemId { get; set; }

    public string ItemNo { get; set; }

    public virtual NumericItem NumericItem {get;set;} //navigation

}


public class NumericItem
{  //This is a subset of the Item entity

    public Item Item { get; set; }

    public int ItemNo { get; set; } //this is a primary key, different type

}

public class NumericItemConfiguration : EntityTypeConfiguration<NumericItem>
{

    public NumericItemConfiguration()
    {
        HasKey(n => n.ItemNo);

        HasRequired(n => n.Item).WithOptional(i => i.NumericItem).Map(m => m.MapKey("ItemId"));

    }

}

public class MyContextContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // do your stuff, and add your configuration here...

        modelBuilder.Configurations.Add(new NumericItemConfiguration());

    }
}

或者你可以不用这个 NumericItemConfiguration class,直接在你的 OnModelCreating 方法中进行配置:

public class MyContextContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // do your stuff, and add your configuration here...

        modelBuilder.Entity<NumericItem>().HasKey(n => n.ItemNo);

        modelBuilder.Entity<NumericItem>().HasRequired(n => n.Item).WithOptional(i => i.NumericItem);

    }
}

请注意,我必须从 NumericItem class 中删除您的 ItemId 属性,否则 EF 会这样抱怨:

ItemId: Name: Each property name in a type must be unique. Property name 'ItemId' is already defined.