10

關係我有一個用戶模型,並在自己的項目中事件模型。該事件具有創建者(用戶)並且具有參與者(用戶),因此事件與用戶具有一對多關係,並且與同一個表具有多對多關係。實體框架代碼優先:1,到許多和許多一對多到同一個表

我第一次一個一對多這樣的關係:

Public class Event 
{ 
     ... 
     public int CreatedById { get; set; } 
     public virtual User CreatedBy { get; set; } 
     ... 
} 

然後當我加入了許多一對多的關係遷移不會產生多對多的關係:

Public class User 
{ 
     ... 
     public virtual ICollection<Event> Events { get; set; } 
     ... 
} 

Public class Event 
{ 
     ... 
     public int CreatedById { get; set; } 
     public virtual User CreatedBy { get; set; } 
     public virtual ICollection<User> Users { get; set; } 
     ... 
} 

如果刪除了一對多的關係那麼遷移產生許多一對多關係成功。

有沒有辦法做到這一點只有數據註釋?

+0

你說得對@slauma,原諒我的英語不是我的母語,我只是盡力做到最好。 – Escobar5 2013-02-27 20:29:58

+0

我編輯它,希望更清楚 – Escobar5 2013-02-27 20:31:57

+0

我不是指一種語言的東西,但內容(如果有任何錯誤信息或例外等,或者如果結果不是你所期望的等)。無論如何,沒關係,問題似乎已經解決:) – Slauma 2013-02-27 21:01:22

回答

15

EF不知道從哪裏User.Events必須映射到。它可能是Event.CreatedBy或它可能是Event.Users。兩者都會導致一個有效的模型。你必須給EF你想通過應用[InverseProperty]屬性有什麼小提示:

public class User 
{ 
    ... 
    [InverseProperty("Users")] 
    public virtual ICollection<Event> Events { get; set; } 
    ... 
} 
+0

完美!就是這樣 – Escobar5 2013-02-27 20:28:37

8

隨着代碼第一種方式,我總是建議使用流利的API,而不是使用DataAnnotations,它會自動使用一些轉換。

這樣,你就會知道你做了什麼確切的配置。

如果我是你,這裏是我會用什麼:

public class EventMap : EntityTypeConfiguration<Event> 
{ 
    public EventMap() 
    { 
     this.HasRequired(m => m.CreatedBy) // envent must have a creator 
      .WithMany() // a user can have 0,1 or more events created by him 
      .HasForeignKey(m => m.CreatedById) // specify property to be used as FK 
      .WillCascadeOnDelete(true); // delete all events created by user if that specific user is deleted 

     this.HasMany(m=>m.Users) // an event can have 0,1 or more participants 
      .WithMany(m=>m.Events) // a user can be a participant in 0,1 or more events     
      .Map(m => m.MapLeftKey("EventId").MapRightKey("UserId")); // this will generate intermediate table to hold participant information - dbo.EventUser with EventId & UserId 
      // Cascade Delete is always true for Many to Many mapping. however, it doesn't delete entry in other table, it deletes entry in Joined Table only. 
    } 
} 
相關問題