【问题标题】:Why is this column getting generated in EF Code-First migrations?为什么在 EF Code-First 迁移中会生成此列?
【发布时间】:2013-11-06 01:21:09
【问题描述】:

我有一个导师实体,其中有学生和导师作为 FK:

    [Required]
    public int MentorId { get; set; }
    public virtual User Mentor { get; set; }

    [Required]
    public int StudentId { get; set; }
    public virtual User Student { get; set; }

用户模型:

    public virtual ICollection<Mentorship> Mentorships { get; set; }

流畅的 API:

    modelBuilder.Entity<Mentorship>()
        .HasRequired(c => c.Mentor)
        .WithMany()
        .HasForeignKey(u => u.MentorId);

    modelBuilder.Entity<Mentorship>()
        .HasRequired(c => c.Student)
        .WithMany()
        .HasForeignKey(u => u.StudentId);

在我的数据库中,我看到了正确填充的 StudentId 和 MentorId 列,但我还看到了一个没有被任何东西使用的 User_UserId 列。我做错了什么?

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:

    您使用了 WithMany() 重载,该重载将关系配置为必需:许多关系的另一端没有导航属性 - 但您在关系的另一端确实有导航属性。

    试试这个:

    modelBuilder.Entity<Mentorship>()
        .HasRequired(c => c.Mentor)
        .WithMany(d => d.Mentorships)
        .HasForeignKey(u => u.MentorId);
    
    modelBuilder.Entity<Mentorship>()
        .HasRequired(c => c.Student)
        .WithMany(d => d.Mentorships)
        .HasForeignKey(u => u.StudentId);//oops! just realised that we just 
                                         //specified that Mentorships is using MentorId 
                                         //as the FK
    

    参考资料:

    Required WithMany Method

    Why do I get an extra foreign key?

    编辑 刮那个。刚刚意识到您正在尝试创建两个关系,而在多方面只有一个导航属性。您不能拥有具有 2 个外键的导航属性。您需要在User 端引入继承或从User 类中删除Mentorships 导航属性或引入单独的StudentMentorshipsMentorMentorships 导航属性

    编辑 2 定义单独的导航属性后查找用户

    int userId = 123;//the one we want to find
    var user = Users.Where(x => x.StudentMentorships.Any(s => s.StudentID == userId) 
                             || x.MentorMentorships.Any(s => s.MentorID == userId);
    

    【讨论】:

    • 在两个映射之一(可能是第二个)中使用不带 lambda 参数的 WithMany() 也可以。这意味着Mentorships 集合仅属于第一个关系,而第二个关系没有反向集合。
    • @Slauma 是的。所以 StudentMentorshipsMentorMentorships 单独使用。
    • 哇,没想到。感谢您的解释。我希望 .Mentorships 列出该学生的 PK 在任一导师的 FK 中列出的所有导师。如果您有时间演示如何做到这一点或任何指示,任何帮助都会很棒。
    • @RobVious 不确定我完全理解你的意思,但我已经添加了如何询问单独的导航属性以获取一个或另一个中的用户
    • 谢谢科林 - 我看到了编辑。这可能会离题,但我仍然有兴趣使用 .Mentorships 来访问这两者,因为在我的代码中,这就是我现在获取它们的方式 - 也许我可以在该导航属性的 Getter 中定义一些东西来做两者都有?
    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多