2015-11-27 83 views
0

有2類EF一個一對多檢索外鍵,但不反對

事件

public class Event 
{ 

    public Guid? UserID { get; set; } 

    [ForeignKey("UserID")] 
    public virtual User User { get; set; } 
... 

用戶

public class User 
{ 
    public Guid UserId { get; set; } 
    // Not used in this example, but just thought they might be related to problem 
    private List<Event> _attendedEvents; 
    public virtual ICollection<Event> AttendedEvents 
    { 
     get { return _attendedEvents ?? (_attendedEvents = new List<Event>()); } 
     set { 
      if (value == null) 
       _attendedEvents = new List<Event>(); 
      else 
       _attendedEvents = new List<Event>(value); 
     } 
    } 
    public virtual ICollection<Event> HostedEvents { get; set; } 
... 

EventConfiguration

HasOptional<User>(s => s.User) 
    .WithMany(s => s.HostedEvents) 
    .HasForeignKey(s => s.UserID); 
  1. 我想要做的事情是
  2. 添加用戶到資源庫
  3. 添加事件(這在其內部具有相同的用戶)到資源庫
  4. 保存更改
  5. 從庫中獲取事件回

所有類型的作品,除了當我檢索事件回它有空用戶,但UserId是有效的,並指向我以前創建的用戶。

以下是我正在做

// Creates just the User object with specified UserName 
var user = ObjectHelpers.CreateUser("ServiceTestUser"); 

// Adds to Repository + Saves Changes 
_client.AddUser(user); 

// Find it again to have generated Id and kind of test if it was added 
user = _client.FindUserByEmail(user.Email); 

// Create Event object and assign specified user object to it 
// At this point @event has User set to above one and UserID null 
      var @event = ObjectHelpers.CreateEvent(user); 

// Attach User from Event + Add Event to repository + Save Changes 
_client.AddEvent(@event); 

// Get it back to Check if everything went fine 
// At this point @event has User set to null and valid UserID 
@event = _client.GetEventByTitle(@event.EventTitle); 
+0

GetEventByTitle實際上在做什麼? –

+0

返回第一個或默認的事件匹配標題屬性,我沒有提到 –

回答

2

默認情況下EF將無法讀取相關的實體。這種行爲非常有用。如果不是這樣,每當你試圖從數據庫中讀取一個實體時,你都會閱讀該實體,並且可能是非常大的相關實體樹。

您必須閱讀realted實體:明確

  • ,通過使用.Include()
  • 或含蓄,通過使用延遲加載,這意味着訪問提供DbContext hasnot被設置在導航屬性

Include()的示例:

DbCtx.Events.First(ev => ev.Title == "title").Include(ev => ev.User); 

有關包括相關實體的更多信息,請參閱:Loading Related Entities