实体框架多对多自引用 [英] Entity Framework many-to-many self-reference
问题描述
public class Employee
{
#region属性
public int EmployeeID {get;组; }
public string FirstName {get;组; }
public string LastName {get;组; }
public int? ManagerID {get;组; }
public Employee Manager {get;组; }
#endregion
}
和modelBuilder: / p>
modelBuilder.Entity< Employee>()。
HasOptional(e => e.Manager)。
WithMany()。
HasForeignKey(m => m.ManagerID);
如何创建一个具有自我参考的实体,在我的情况下,有朋友(如果是朋友b这意味着b是a)和老师的朋友(如果a是b的老师,b是a的学生)?
对不起,如果已经存在类似的线程。
非常感谢任何帮助。
好的,因为很多人回答这个;),我搜索再多一点,我找到了我的案例的解决方案。实体看起来像:
public class User
{
public int ID {get;组; }
public string UserName {get;组; }
public virtual ICollection< User>朋友{get;组;
}
modelBuilder:
$ b $ H $ M $($)
.WithMany();
最后我做了帮助方法BeFriend和BecomeTeacher学习,这确保当你和某人成为朋友时成为你的朋友(以及教师学生的各自的东西)。
I have an entity User. Each User is supposed to have many Friends and Teachers. With EF Code First I am a little bit confused on how to achieve what I want. I saw examples of self reference, but not many-to-many. For example:
public class Employee
{
#region Properties
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? ManagerID { get; set; }
public Employee Manager { get; set; }
#endregion
}
and the modelBuilder:
modelBuilder.Entity<Employee>().
HasOptional(e => e.Manager).
WithMany().
HasForeignKey(m => m.ManagerID);
How to create an entity with self-reference in my case, where there are Friends (if a is friend with b this means that b is friend with a) and Teachers (if a is teacher of b, b is student of a)?
Sorry if there already exists a similar thread. Any help is greatly appreciated.
Ok, so because a lot of people answered this ;), I searched a little more and I found the solution for my case. The entity looks like:
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public virtual ICollection<User> Friends { get; set; }
}
The modelBuilder:
modelBuilder.Entity<User>()
.HasMany(x => x.Friends)
.WithMany();
And finally I made helper methods BeFriend and BecomeTeacherStudent, which make sure that when you become friend with someone he becomes friend with you (and the respective thing for teacher-student).
这篇关于实体框架多对多自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!