实体框架多对多自引用 [英] Entity Framework many-to-many self-reference

查看:170
本文介绍了实体框架多对多自引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体用户。每个用户应该有很多朋友和老师。使用EF代码首先我有点困惑如何实现我想要的。我看到自我参考的例子,但不是很多对。例如:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆