簡體   English   中英

實體框架代碼優先:使用引用表映射ID到實體的列表

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

假設我有一個現有的實體EmailNotification和另一個實體User。 我希望我的EmailNotification包含可以發送到的用戶列表。 我認為從數據庫角度可以實現的是我們創建了一個額外的表,如下所示:

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)。

在nutsell你需要我認為是在EmailNotification和User之間創建多對多關系,如果案例是一個用戶可以包含在很多通知中,一個通知可以包含很多用戶那么你需要以下構造

    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");
                    });
    }

在這種情況下,您有多對多的關系:

楷模:

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將隱式創建表:User2EmailNotification包含列:UserID和EmailNotificationID。

PS如果您同樣想要創建表UserGroup,從EmailNotification類訪問用戶將很難(或不舒服),相反,您應該在此類中聲明UserGroup屬性,因此Users和EmailNotifications之間的關系將是間接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM