Skip to main content
 首页 » 编程设计

c#之Entity Framework 代码优先 : map list of ids to entity using reference table

2024年04月18日35jackei

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

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 进行设置)。

请您参考如下方法:

简而言之,我认为您需要在 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; } 
    } 

要自定义多对多表创建,您可以覆盖 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"); 
                    }); 
    }