首页 > 解决方案 > 自引用多对多类不返回 .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 很陌生。

标签: c#linqasp.net-coreentity-framework-coreasp.net-core-2.0

解决方案


推荐阅读