c# - 自引用多对多类不返回 .NET Core 2.0 中的集合
问题描述
我正在构建一个 asp.NET Core 2.0 MVC 应用程序。我有以下自引用类:
public class ProductCategory
{
public int ID { get; set; }
public string Name { get; set; }
[DataType(DataType.Html)]
public string Description { get; set; }
public int DisplayOrder { get; set; }
public int MenuIconXPosition { get; set; }
public int MenuIconYPosition { get; set; }
public virtual ICollection<ProductSubCategory> ParentCategory { get; set; }
public virtual ICollection<ProductSubCategory> ChildCategory { get; set; }
public ICollection<ProductProductCategory> ProductProductCategories { get; set; }
}
使用以下关系类:
public class ProductSubCategory
{
public int ChildCategoryId { get; set; }
public virtual ProductCategory ChildCategory { get; set; }
public int ParentCategoryId { get; set; }
public virtual ProductCategory ParentCategory { get; set; }
}
在我的 dbContext.cs 文件中,我有以下内容:
modelBuilder.Entity<ProductSubCategory>()
.HasKey(p => new { p.ChildCategoryId, p.ParentCategoryId });
modelBuilder.Entity<ProductSubCategory>()
.HasOne(p => p.ParentCategory)
.WithMany(p => p.ChildCategory)
.HasForeignKey(p => p.ParentCategoryId);
modelBuilder.Entity<ProductSubCategory>()
.HasOne(p => p.ChildCategory)
.WithMany(p => p.ParentCategory)
.HasForeignKey(p => p.ChildCategoryId);
数据库迁移和更新按预期构建。用数据填充它,它似乎按预期工作。使用以下 LINQ 查询遍历数据时:
var result = _context.ProductCategories
.AsNoTracking()
.Include(i => i.ParentCategory)
.Include(i => i.ChildCategory)
.OrderBy(i => i.DisplayOrder);
预期的结果类似于Result -> ICollection<ProductCategory> -> ICollection<ProductSubCategory> -> ICollection<ProductCategory>
但有时最终的 ICollection 为空。
有时ChildCategory
集合返回 null。ChildCategoryId
总是分配的,所以我知道它映射正确。最奇怪的部分是,ChildCategory
返回 null 的集合取决于OrderBy
函数。结果中的哪些返回 null 而不是预期的集合似乎是完全任意的。
知道我错过了什么或不理解吗?我对 asp.NET 很陌生。
解决方案
推荐阅读
- python - Spark:无法运行程序“jupyter”
- firebase - 如何区分 Firebase Auth 中的初始化状态和非用户状态?
- ios - 如何以编程方式使用自动布局调整多个 iOS 屏幕尺寸的视图大小
- javascript - 如果 this.setState 不起作用,为什么 this.state = wrong?
- javascript - 如何为反应路由器组件设置独特的背景图像?
- oracle - apex_web_service.make_rest_request 的长度要求错误?
- python - 如何使多个文本小部件扩展以填充 Tkinter 中的框架
- spring - 如何在 Spring 中访问缓存值
- mysql - 如何从 Sequelize 中与主模型相同级别的包含模型返回结果?
- typescript - 如何推断 TypeScript 中的可选属性?