非密钥上的EF零对一FLUENT API外键

时间:2017-01-05 22:07:16

标签: entity-framework ef-fluent-api

我有一个遗留数据库已经破坏了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代码,NumericItem始终具有Item和Item可能有也可能没有NumericItem。基数始终为零/一

1 个答案:

答案 0 :(得分:0)

这是外国唯一密钥的情况。

通常,如果关系为0或1的主体实体(如Item)和可选的依赖(NumericItem),则从属主键也是主体的外键。在你的情况下,因为数据库已经是这样的,你可以这样做:

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课程的情况下执行此操作,直接在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);

    }
}

请注意我必须从ItemId课程中移除您的NumericItem媒体资源,否则EF会抱怨这样:

  

ItemId:Name:类型中的每个属性名称必须是唯一的。属性   name&#39; ItemId&#39;已定义。