Entity Framework 代码优先:使用引用 table 将 ID 列表映射到实体

Entity Framework Code First: map list of ids to entity using reference table

假设我有一个现有实体 EmailNotification 和另一个实体 User。我希望我的 EmailNotification 包含可以将其发送到的用户列表。正如我所看到的,从数据库的角度来看,我们可以创建一个额外的 table,如下所示:

CREATE TABLE UserGroup (UserGroupID INT NOT NULL, UserID INT NOT NULL)

并在 EmailNotification 中添加一个 UserGroupID 列。

但是,问题是我想不出如何使用 EntityFramework Code First 方法来做到这一点,这样我就可以在 EmailNotification 中有一个用户列表。我想要类似

的东西
EmailNotification
{
  public virtual IEnumerable<User> Users { get; set; }
}

但我不知道如何使用 EntityFramework 进行上述映射(最好从 DbContext 而非 FluentAPI 进行设置)。

在这种情况下,您有多对多关系:

型号:

public class EmailNotification
{
    public int ID { get; set; }
    //other stuff...
    public virtual ICollection<User> Users { get; set; }
}

public class User
{   
    public int ID { get; set; }
    //other stuff...
    public virtual ICollection<EmailNotification> EmailNotifications { get; set; }
}

因此,EF 将隐式创建 table: User2EmailNotification 列:UserID 和 EmailNotificationID。

P.S. If you, all the same, want to create table UserGroup, it will be hard (or not comfortable) to access Users from EmailNotification class, instead you will should to declare UserGroup property inside this class, so relation between Users and EmailNotifications will be indirect.

简而言之,我认为您需要在 EmailNotification 和用户之间创建多对多关系,如果情况是一个用户可以包含在很多通知中,而一个通知可以包含很多用户,那么您需要以下构造

    public class User
    {

        public int UserId{ get; set; } /*your properties*/  

        public virtual ICollection<EmailNotification> Courses { get; set; }
    }
    public class EmailNotification
    {

        public int EmailNotificationId{ get; set; } /*your properties*/  

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

要自定义多对多 table 创建,您可以覆盖 OnModelCreating

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany<EmailNotification>(s => s.EmailNotification)
            .WithMany(c => c.User)
            .Map(cs =>
                    {
                        cs.MapLeftKey("UserId");
                        cs.MapRightKey("EmailNotificationId");
                        cs.ToTable("UserEmailNotifications");
                    });
    }