为什么在EF Code-First迁移中生成此列?

时间:2013-11-06 01:21:09

标签: entity-framework ef-code-first

我有一个导师实体,其中有学生和导师作为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; }

Fluent 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列。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您已使用WithMany()重载来配置所需的关系:许多在关系的另一侧没有导航属性 - 但您在关系的另一侧确实有导航属性。 / p>

试试这个:

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方面引入继承或从Mentorships类中删除User导航属性,或者引入单独的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);