如何包含 Entity Framework 的关联实体?

How to include associated entities with Entity Framework?

创建的数据库模式具有以下关系

用于生成上述模式的模型是

 public class Option
    {
        public int OptionId { get; set; }
        public string OptionName { get; set; }
    }

    public class Value
    {
        public int ValueId { get; set; }
        public string OptionValue { get; set; }
    }

    public class Sku
    {
        public int SkuId { get; set; }

        public int ProductId { get; set; }

        public decimal Price { get; set; }

        [ForeignKey("ProductId")]
        public Product Product { get; set; }
    }

    public class ProductVariant
    {
        public int Id { get; set; }

        public int ProductId { get; set; }

        public int OptionId { get; set; }

        public int ValueId { get; set; }

        public int SkuId { get; set; }

        [ForeignKey("ProductId")]
        public Product Product { get; set; }

        [ForeignKey("OptionId")]
        public Option Option { get; set; }

        [ForeignKey("ValueId")]
        public Value Value { get; set; }

        [ForeignKey("SkuId")]
        public Sku Sku { get; set; }
    }

而产品 class 是

public class Product
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public IEnumerable<ProductVariant> ProductVariants { get; set; }
}

如何使用此布局加载相关实体?

我尝试了以下方法,但 OptionsValuesSkus 无法作为导航属性访问

        var products = context.Products
            .Include(x => x.ProductVariants)
            .Include(x => x.Options)
            .Include(x => x.Values)
            .Include(x => x.Skus)

我应该做哪些改变?

您的产品 属性 缺少导航 class:

public IEnumerable<Sku> Skus { get; set; }

并且在获取嵌套实体时需要使用 .ThenInclude 而不是 .Include。它将是:

var products = context.Products
               .Include(x => x.Skus)
               .Include(x => x.ProductVariants)
                   .ThenInclude(ProductVariants => ProductVariants.Options)
               .Include(x => x.ProductVariants)
                   .ThenInclude(ProductVariants => ProductVariants.Values)