简体   繁体   English

EntityFramework自动创建多对多关系

[英]EntityFramework creating many-to-many relationships automatically

Does Entity Framework create Many-Many relationships automatically and if so how? 实体框架是否自动创建多对多关系?

I am trying this below: 我在下面尝试:

public DbSet<User> Users { get; set; }
public DbSet<Sport> Sports { get; set; }
public DbSet<Team> Teams { get; set; }
  • I have many Sports 我有很多运动
  • I have many Teams in a Sport 我有很多运动队
  • I have many Users in a Team 我的团队中有很多用户

Classes: 类:

Sport 运动

public int ID { get; set; }
public List<Team> Teams { get; set; }

Team 球队

public int ID { get; set; }
public List<User> Members { get; set; }
public int SportID { get; set; }

User 用户

 public int UserID { get; set; }

Issue: 问题:

So it creates the tables Users, Sports, Teams fine with their foreign key associations to each other. 因此,它可以很好地创建表Users,Sports,Teams及其相互之间的外键关联。 The problem is that these tables are not normalized and have redundant data. 问题在于这些表没有被规范化并且具有冗余数据。 Also, when trying to query for members in the Teams table, I always get a null Members List! 另外,当尝试在“团队”表中查询成员时,我总是得到一个空的成员列表!

For Example, Users has a column Team_ID so it creates a new User record when added to a team which is bad! 例如,“用户”有一个“团队ID”列,因此添加到团队中时会创建一个新的“用户”记录,这很糟糕!

Shouldn't Entity Framework create a Many-Many relationship table automatically? 实体框架是否不应该自动创建多对多关系表? So that it has columns |UserID|SportID|TeamID| 使其具有列| UserID | SportID | TeamID |

Users has a column Team_ID 用户有一个列Team_ID

Here is the problem. 这是问题所在。 EF created a column in User table because you told EF to do so. EF在用户表中创建了一个列,因为您告诉EF这样做。 You should make it many-to-many. 您应该使其多对多。

public class User
{
   public int UserId { set;get;}
   public ICollection<Team> Teams { set; get; }
}
public class Sport
{
    public int Id { set; get; }
    public string Name { set; get; }
    public IEnumerable<Team> Teams { set; get; }
}

public class Team
{
    public int TeamId { get; set; }
    public List<User> Users { get; set; }
    public int SportId { set; get; }
}

Now using fluent configuration, you can instruct EF to create a junction table for the many to many relation ship. 现在,使用流利的配置,您可以指示EF为多对多关系船创建连接表。 You can do this in the OnModelCreating method of your dbcontext class. 您可以在dbcontext类的OnModelCreating方法中执行此操作。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                .HasMany(d => d.Teams)
                .WithMany(f => f.Users)
                .Map(w => w.ToTable("UserTeam")
                           .MapLeftKey("UserId")
                           .MapRightKey("TeamId"));

}

This will establish a many- to many relationship between User and Team and create a fourth table which has a UserId and TeamId column. 这将在User和Team之间建立多对多关系,并创建第四个表,其中包含UserId和TeamId列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM