简体   繁体   English

如何在实体框架中包含关联实体?

[英]How to include associated entities with Entity Framework?

The database schema created has the following relations创建的数据库模式具有以下关系

在此处输入图像描述

The models used for generating the schema above are用于生成上述模式的模型是

 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; }
    }

while the product class is而产品 class 是

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

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

How can i load realated entities with this layout?如何使用此布局加载关联实体?

I tried the following but Options , Values and Skus are not accesible as navigation properties我尝试了以下方法,但OptionsValuesSkus无法作为导航属性访问

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

What changes should i make?我应该做些什么改变?

You lack navigation property in your product class:您的产品 class 中缺少导航属性:

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

And you need to use.ThenInclude instead of.Include when you are getting nested entities.当您获取嵌套实体时,您需要使用.ThenInclude 而不是.Include。 It would be:这将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM