Entity Framework 核心 (EF 7) 多对多结果始终为空

Entity Framework Core (EF 7) many-to-many results always null

我已按照 Issue #1368 and the Docs Here 中描述的多对多变通方法进行操作...但是当我尝试导航时,它始终 returns 为空。

我的模特:

    public class Organization
{
    public Guid OrganizationID { get; set; }

    //...

    public ICollection<OrganizationSubscriptionPlan> OrganizationSubscriptionPlans { get; set; }

}

public class SubscriptionPlan
{
    public int SubscriptionPlanID { get; set; }

    //...

    public ICollection<OrganizationSubscriptionPlan> OrganizationSubscriptionPlans { get; set; }


public class OrganizationSubscriptionPlan
{
    [ForeignKey("Organization")]
    public Guid OrganizationID { get; set; }
    public Organization Organization { get; set; }

    [ForeignKey("SubscriptionPlan")]
    public int SubscriptionPlanID { get; set; }
    public SubscriptionPlan SubscriptionPlan { get; set; }
}

ApplicationDbContext:

    protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.Entity<OrganizationSubscriptionPlan>().HasKey(x => new { x.OrganizationID, x.SubscriptionPlanID });
    builder.Entity<OrganizationSubscriptionPlan>().HasOne(x => x.Organization).WithMany(x => x.OrganizationSubscriptionPlans).HasForeignKey(x => x.OrganizationID);
    builder.Entity<OrganizationSubscriptionPlan>().HasOne(x => x.SubscriptionPlan).WithMany(x => x.OrganizationSubscriptionPlans).HasForeignKey(x => x.SubscriptionPlanID);
}

我的查询:

var organizations = _context.Organizations
    .Include(o => o.OrganizationSubscriptionPlans);

foreach (var organization in organizations)
{
    //....
    var subscriptions = organization.OrganizationSubscriptionPlans
            .Select(s => s.SubscriptionPlan);
     // ^^^^^^^^^^^ why is subscriptions always null?
}

"organizations" 查询 returns 结果符合预期,包括每个中的 OrganizationSubscriptionPlans 列表,但是当我尝试在 foreach 循环中导航到它们时 "subscriptions" 查询returns 每次都为空。我做错了什么?

ForeignKey 属性用于装饰引用属性以指示它们是什么原语 属性 持有 FK 值。

public class OrganizationSubscriptionPlan
{    
    public Guid OrganizationID { get; set; }
    [ForeignKey("OrganizationID")]
    public Organization Organization { get; set; }

    public int SubscriptionPlanID { get; set; }
    [ForeignKey("SubscriptionPlanID")]
    public SubscriptionPlan SubscriptionPlan { get; set; }
}

原来是延迟加载问题。您必须 "Include" 加入实体,然后 "ThenInclude" 另一个实体。

var organizations = _context.Organizations
    .Include(o => o.OrganizationSubscriptionPlans)
    .ThenInclude(s => s.SubscriptionPlan);