2016-01-22 25 views
3

所以我有一個非常奇怪的問題,當使用EF有時一個類的屬性爲null,有時它不是。在這種情況下ParentType的往往是空,當它應該有一個值C#實體框架屬性是(有時)空

用下面的代碼確實有一個值:

 using (Context context = new Context()) 
     { 
      checkedListBox_SubTypes.DataSource = context.Types.Where(x => x.ParentType != null && x.ParentType.TypeID == _selectedType.TypeID).ToList(); 
     } 
這一行代碼,在那裏我試圖讓

然而同一個對象背出一個列表框,它ParentType的變成空

下面是我的課和DB圖的事情是如何設置:

public class Type 
{ 
    #region Fields 
    #endregion Fields 

    #region Constructor 
    public Type() 
    { 

    } 
    #endregion Constructor 

    #region Properties 
    public int? TypeID { get; set; } 

    [DisplayName("Type")] 
    public string TypeName { get; set; } 

    public Type ParentType { get; set; } 

    /// <summary> 
    /// List of Types this Type is associated with (Parent/Sub) 
    /// </summary> 
    public virtual ICollection<Type> Types { get; set; } 

    public virtual ICollection<Object> Objects { get; set; } 
    #endregion Properties 

語境:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 

     //Set Many-To-Many relationship Mapping between Object & Type 
     modelBuilder.Entity<ObjectType>() 
      .HasMany(x => x.Objects) 
      .WithMany(x => x.Types) 
      .Map(m => m.ToTable("ObjectType") 
      .MapLeftKey("TypeID") 
      .MapRightKey("ObjectNumber")); 


     //Set One-To-Many relationship Mapping between Type &(Parent)Type 
     modelBuilder.Entity<Type>() 
      .HasMany(x => x.Types) 
      .WithOptional(x => x.ParentType) 
      .Map(m => m.ToTable("Type") 
      .MapKey("ParentTypeID")); 

} 
+0

你確定你有那些你在哪裏得到這個屬性爲NULL記錄數據? – Shyju

+2

最有可能與延遲加載有關。你嘗試過'包括'嗎?不要被Where子句欺騙,它根本不處理對象。 –

+0

@Shyju是的,我絕對是積極的我有這些記錄的數據 – Michael

回答

2

我很確定你的第一個代碼片段ParentMatterType也是null。讓我們改變它一點點:

using (LitTrackContext context = new LitTrackContext()) 
{ 
    var types = context.MatterTypes 
         .Where(x => x.ParentMatterType != null 
           && x.ParentMatterType.MatterTypeID == _selectedMatterType.MatterTypeID) 
         .ToList(); 
    checkedListBox_MatterSubTypes.DataSource = types; 
} 

如果您在調試器檢查types你會看到,有沒有ParentMatterType在裏面。這是因爲該屬性不是virtual,因此它不會被加載(如果您在調試器中檢查它,會發生這種情況)。

即使您製作屬性virtual以後也無法看到其內容,因爲上下文立即處理(順便說一句,這很好)。如果您以後嘗試訪問ParentMatterType,則EF會拋出異常。

則應該Include在您的查詢的性能,通過改變第一部分:

var types = context.MatterTypes.Include(m => m.ParentMatterType) 
... 
+0

現貨解決方案。這使它的工作,並解釋是好:) 我唯一的問題是,爲什麼我必須「包含」ParentMatterType但不包括「包括」屬性,如MatterTypeName或MatterTypeID。是因爲複雜的類型vs原始類型,還是它與導航屬性有關? – Michael

+0

是的,這是因爲它是導航屬性。 –

-1

我有同樣的問題檢索數據源,一旦它已經綁定到一個控制,在我的情況DataGrid中。我從來沒有想過爲什麼這是或進一步調查。要解決這個問題,我通常要做的就是在將對象分配給控件之前,在Session或ViewState或類級別變量中保留對象的引用。所以稍後,如果我需要的話,我仍然會提供對象的引用。

+0

啊。我看到你在那裏做了什麼。首先創建一個對數據源的引用,就像我在之前的文章中說的那樣,說originalList。然後從那裏找到該項目: foreach(var item in checkListBox。已選項目) { var smt = originalList.Where(m => m.MatterNumber == item.value).FirstOrDefault(); } –

+1

不要這樣做。 ViewState在頁面之間導航時不可靠,並且如果要在會話中存儲某些內容,請勿像上面那樣存儲整個對象。另外,OP已將其標記爲「winforms」,它是無狀態的,並且沒有會話或視圖狀態的概念。 – ragerory