所以我有一個非常奇怪的問題,當使用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"));
}
你確定你有那些你在哪裏得到這個屬性爲NULL記錄數據? – Shyju
最有可能與延遲加載有關。你嘗試過'包括'嗎?不要被Where子句欺騙,它根本不處理對象。 –
@Shyju是的,我絕對是積極的我有這些記錄的數據 – Michael