我有一个导师实体,其中有学生和导师作为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列。我做错了什么?
答案 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
参考文献:
Why do I get an extra foreign key?
修改强>
抓一点。刚刚意识到你试图创建两个关系,只有一个导航属性在很多方面。您不能拥有包含2个外键的导航属性。您需要在User
方面引入继承或从Mentorships
类中删除User
导航属性,或者引入单独的StudentMentorships
和MentorMentorships
导航属性
编辑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);