實體框架核心(EF 7)多對多結果始終為空

entity-framework-core

我已按照問題#1368Docs Here中描述的多對多解決方法的說明進行操作......但是當我嘗試導航時,它總是返回null。

我的模特:

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

“組織”查詢按預期返回結果,包括每個組織中的OrganizationSubscriptionPlans列表,但是當我嘗試在foreach循環中導航到它們時,“subscriptions”查詢每次都返回null。我究竟做錯了什麼?

一般承認的答案

原來這是一個延遲加載問題。您必須“包含”加入實體,然後“ThenInclude”另一個實體。

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

熱門答案

ForeignKey attr用於修飾引用屬性以指示它們保存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; }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因