【问题标题】:Entity Framework One to many fluent Api - foreign key实体框架一对多流利的Api - 外键
【发布时间】:2015-10-13 07:11:16
【问题描述】:

我想在两个实体之间建立联系。

我有 Entity_1 和 Entity_2 的一对多关系(一个 Entity_1 可以有多个 Entity_2)。

所以我有我的实体: 实体

    class Entity_1
    {    
        public int Id { get; set; }
        public int Entity_2Id{ get; set; }
        public virtual Entity_2 Entity_2{ get; set; } 
    }

    class Entity_2
    {    
        public int Id { get; set; }
        public int Entity_2Id{ get; set; }
        public virtual ICollection<Entity_1> Entity_1s{ get; set; }
    }

我如何才能建立我在实体 2 中有外键 (Entity_1) 的连接?

【问题讨论】:

    标签: c# .net entity-framework mapping ef-fluent-api


    【解决方案1】:

    一个Entity_1可以有多个Entity_2

    这意味着Entity_1(可选)具有Entity_2 的集合,而Entity_2(可选)具有对Entity_1 的引用:

    class Entity_1
    {    
        public int Id { get; set; }
        public virtual ICollection<Entity_2> Entity_2s{ get; set; }
    }
    
    class Entity_2
    {    
        public int Id { get; set; }
        public int Entity_1Id { get; set; }
        public virtual Entity_1 Entity_1 { get; set; }
    }
    

    当您的实体不正确时。 上面代码的 Fluent API 是:

    HasRequired(_ => _.Entity_1)
        .WithMany(_ => _.Entity_2s)
        .HasForeignKey(_ => _.Entity_1Id);
    

    更多选项here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多