0

我有一个导师实体,其中有学生和导师作为 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 列。我做错了什么?

4

1 回答 1

1

You have used the WithMany() overload that configures the relationship to be required:many without a navigation property on the other side of the relationship - but you do have a navigation property on the other side of the relationship.

Try this:

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

References:

Required WithMany Method

Why do I get an extra foreign key?

Edit Scratch that. Just realised you are trying to create two relationships with only one navigation property on the many side. You can't have a navigation property with 2 foreign keys. You need to introduce inheritance on the User side or remove the Mentorships navigation property from the User class or introduce separate StudentMentorships and MentorMentorships navigation properties

Edit 2 Finding a user once you've defined separate navigation properties

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);
于 2013-11-06T05:33:49.433 回答