EF自我一对多关系

时间:2016-05-24 10:34:24

标签: c# entity-framework

我想与EF6实现一对多的关系。表User可以处理许多Friends,我可以使用map表实现该表:

--TABLE USERS:
Id

--TABLE USER_MAP:
UserOwnerId
UserFriendId

但是如何用EF6实现呢?

这是我的实体User

public class User
{
    ...
    public virtual List<User> Friends { get; set; }
    ...
}

3 个答案:

答案 0 :(得分:1)

你可以使用这样的东西

//关系

HasRequired(t => t.User)
            .WithMany(t => t.Friends)
            .HasForeignKey(d => d.UserId);

https://msdn.microsoft.com/en-us/data/hh134698.aspx

答案 1 :(得分:1)

使用DataAnnotations的一对多关系:

  public class User
    {
        public User() { }

        public int UserId { get; set; }
        public string Name { get; set; }

        public virtual Friends friends { get; set; }
    }

    public class Friends
    {
        public Friends()
        {
            Users = new List<User>();
        }
        public int FriendId { get; set; }
        public string Name { get; set; }

        public virtual ICollection<User> Users { get; set; }
    }

答案 2 :(得分:0)

您可以在Code中首先定义:

1)Fluent API:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual Standard Standard { get; set; }
}

public class Standard
{
    public Standard()
    {
        Students = new List<Student>();
    }
    public int StandardId { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

Fleut Api: 在你的DbContext中:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        //one-to-many 
        modelBuilder.Entity<Student>()
                    .HasRequired<Standard>(s => s.Standard) 
                    .WithMany(s => s.Students);

}

虚拟关键字仅适用于延迟加载,如果不需要,可以将其删除

2)代码优先:

public class Student
{
    public Student()
    {
        Students= new List<Student>();
    }

    public int StundendId{ get; set; }

    public string StudentName { get; set; }

    public int? SharedStudentId{ get; set; }

    [ForeignKey("SharedStudentId")]
    public Student SharedStudent{ get; set; }

    public virtual ICollection<Student> SharedStudents{ get; set; }
}