【问题标题】:EF 6 Code First Generated From Database adding ReleationshipEF6 代码首先从数据库生成添加关系
【发布时间】:2015-01-15 19:11:21
【问题描述】:

我有一个现有的数据库,我使用了 nuget 功能“数据库中的代码优先”

在大多数情况下,它似乎运作良好。但是,它并没有获取数据库拥有的所有关键关系。

我有一个名为 Sessions 的表和一个名为 Responses 的表。 Responses 表有一个 SessionId 字段。现在在旧的 EDMX 模型文件中,会话和响应之间存在 1:* 关系。这样我就可以通过foundSession.Responses 获取该会话的响应列表。

Code First From Database 没有创建 Session.Responses 关系。我在会话模型中添加了一个 ICollection。我怀疑我还需要在“OnModelCreating”方法中添加这种关系的设置方式。

我试图做类似的事情:

 modelBuilder.Entity<Session>()
            .HasMany(e => e.Responses)
            .WithMany().Map(m => m.ToTable("Sessions").MapLeftKey("Id").MapRightKey("SessionId"));

但这没有用。它给了我一个错误:“无效的对象名称'dbo.Sessions1'。”

我试图用同样的方法将它从另一行作为基础:

          modelBuilder.Entity<Role>()
            .HasMany(e => e.Users)
            .WithMany(e => e.Roles)
            .Map(m => m.ToTable("RoleUser").MapLeftKey("Roles_Id").MapRightKey("Users_Id"));

但这是多对多的关系。我似乎没有看到任何 1:many。有可能吗?

【问题讨论】:

    标签: c# database entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    我不是 100% 确定如何使用 Fluent API 做到这一点,但您可以使用 Data Annotations 做到这一点:

    在您的Session 班级中:

    public virtual ICollection<Response> Responses { get; set; }
    

    在您的Response 班级中:

    [ForeignKey("MySession")]
    public int SessionID { get; set; }
    
    public virtual Session MySession { get; set; }
    

    【讨论】:

    • 我收到此错误:“Outcomes_Report_Engine.Models.DAL.DbResponse”类型的属性“SessionId”上的 ForeignKeyAttribute 无效。在依赖类型“Outcomes_Report_Engine.Models.DAL.DbResponse”上找不到导航属性“Sessions”。 Name 值应该是有效的导航属性名称。
    • 你把导航属性放在上面了吗?
    • 除了你的解决方案中的两块代码之外吗?
    • 不,这应该是我写的。确保在测试时您没有使用任何试图做同样事情的 Fluent API。
    • 做到了!我错过了响应类公共虚拟会话 MySession { get; 中的第二行。放; }
    【解决方案2】:

    这是一种使用 Fluent Api 创建一对多关系的方法:

     modelBuilder.Entity<Response>().
       HasRequired(e => e.Session).
       WithMany(s=>s.Responses).
       HasForeignKey(m => m.SessionId);
    

    【讨论】:

    • 产品应该是“会话”吗? .Parent 应该是什么? modelBuilder.Entity()。 HasRequired(e => e.Responses)。 HasForeignKey(m => m.SessionId); .HasForeignKey 无法解析,因为 HasRequired e.Responses 是我在 Session 类中设置的 ICollection
    • 如果我将 Product 更改为 Session,那么我无法执行它下面的行 e.Session
    • 您在评论中显示的配置与我的不同。你试过我的配置了吗?
    • modelBuilder.Entity()。 HasRequired(e => e.Session)。 WithMany(s => s.Responses)。 HasForeignKey(m => m.SessionId);不起作用,因为在这种情况下'e'是一个会话,所以我不能做 e.session
    • 但是为什么要更改每个会话的产品?您在评论中显示的配置是错误的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2014-05-07
    相关资源
    最近更新 更多