Asp.net mvc EF 1对多关系始终为空

Asp.net mvc EF 1对多关系始终为空,asp.net-mvc,entity-framework,foreign-keys,entity-relationship,foreign-key-relationship,Asp.net Mvc,Entity Framework,Foreign Keys,Entity Relationship,Foreign Key Relationship,我在颜色和库存表之间有一对多的关系 我的班级: Color.cs: public class Color:Base.BaseEntity { public string ColorName { get; set; } public virtual IList<InventoryEntity.Inventory> Inventories { get; set; } } 我的背景: protected override void OnModelCreating(DbMode

我在颜色和库存表之间有一对多的关系

我的班级: Color.cs:

public class Color:Base.BaseEntity
{
   public string ColorName { get; set; }
   public virtual IList<InventoryEntity.Inventory> Inventories { get; set; }
}
我的背景:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
   base.OnModelCreating(modelBuilder);

   #region Inventory-Colors
     modelBuilder.Entity<Entity.InventoryEntity.Inventory>()
    .HasRequired(m => m.OwnerColor)
    .WithMany(t => t.Inventories)
    .HasForeignKey(m => m.ColorId)
    .WillCascadeOnDelete(false);
   #endregion
}
它总是空的。代码可以找到id=1的库存,但ownercolor为空


我不明白为什么。我有什么遗漏吗?我也有同样的关系。它们工作正常。

您正在混合虚拟关联属性(用于延迟加载)和非虚拟关联属性(用于快速加载):这似乎不是一个好主意。因此,如何解决此问题?请在所有关联属性都为虚拟的情况下进行测试。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
   base.OnModelCreating(modelBuilder);

   #region Inventory-Colors
     modelBuilder.Entity<Entity.InventoryEntity.Inventory>()
    .HasRequired(m => m.OwnerColor)
    .WithMany(t => t.Inventories)
    .HasForeignKey(m => m.ColorId)
    .WillCascadeOnDelete(false);
   #endregion
}
string CName = rpinventory.FirstOrDefault(x => x.Id == 1).OwnerColor.ColorName;