2016-06-10 69 views
1

比方说,我有一个现有的实体EmailNotification和另一个实体用户。我希望我的EmailNotification包含可以发送到的用户列表。在我看来,从数据库的角度来看实现的是,我们创建一个额外的表像下:实体框架代码第一:使用参考表映射到实体的ID列表

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

,并添加UserGroupID列到EmailNotification。

但是,问题在于我无法想象如何使用EntityFramework Code First方法执行此操作,以便我可以在EmailNotification中拥有用户列表。我想是这样

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

,但我不知道我该怎么办使用的EntityFramework提到的映射(最好的DbContext,不FluentAPI设置)。

回答

1

在这种情况下,你有很多一对多的关系:

机型:

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将implicitley创建表:与列User2EmailNotification:用户名和EmailNotificationID。

P.S.如果你同样想创建表UserGroup,那么访问EmailNotification 类的用户将会很难(或不舒服) ,而应该在 这个类中声明UserGroup属性,所以用户和EmailNotifications之间的关系将间接为 。

+0

我曾想过这种做法,但我并不真的需要用户 - > EmailNotificati关于我的情况。是否有可能创建一些分组表,这些分组表只包含一个组ID和一组用户,以便在这种情况下以及在将来的某些组中使用它们? – Seatless

+0

是的,这是可能的,但在这种情况下,您无法声明EmailNotification-> Users,而是它将是EmailNotification-> UserGroup,因此您应该在这些变体之间进行选择。 –

2

在nutsell你需要什么,我认为是创造许多人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"); 
        }); 
    }