首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >非键上的EF零对一FLUENT API外键

非键上的EF零对一FLUENT API外键
EN

Stack Overflow用户
提问于 2017-01-05 22:07:16
回答 1查看 976关注 0票数 0

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

代码语言:javascript
运行
复制
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

}

我如何告诉EF代码,首先使用Fluent API,NumericItem总是有一个项目,项目可能有,也可能没有NumericItem。基数总是为0/1。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-05 22:42:20

这是外部唯一键的情况。

通常,当关系为0或1的关系中具有主体实体(如Item)和可选依赖项(NumericItem)时,依赖主键也是主体的外键。在您的例子中,由于数据库已经是这样的,您可以这样做:

代码语言:javascript
运行
复制
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方法中执行配置:

代码语言:javascript
运行
复制
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:名称:类型中的每个属性名称必须是唯一的。属性名“ItemId”已经定义。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41495567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档