Entity Framework 6 "HasRequired" and "WithMany" partially work - do not work properly

So, after being crazy for 3 hours and everywhere on the Internet, I forced myself to ask here. I have been using Entity Framework for more than 5 years and I have never had the problem described below

I have two POCO classes (edited):

public class Company
{
    public virtual ICollection<BusinessUnit> BusinessUnits { get; protected set; } = new List<BusinessUnit>();

    public int Id { get; protected set; }
}

public class BusinessUnit
{
    public virtual Company Company { get; protected set; } = new Company();

    public int CompanyId { get; protected set; }

    public string Description { get; protected set; }
}

And in my "BusinessUnit" configuration, I declare:

        this
            .HasRequired(c => c.Company)
            .WithMany(c => c.BusinessUnits)
            .HasForeignKey(c => c.CompanyId);

The following works:

  • Individually request 2 objects through their DbSets
  • Access to the N-1 Company navigation property on my extracted BusinessUnit

The following does not work:

  • Navigation property from 1 to N "BusinessUnits" on the restored "Company" object is always NULL, even if you use "Include" for active loading

, , EF , :

  • ( 1 )
  • ( , )
  • ICollection , .
  • "HasRequired" , - "" "BusinessUnit" .

, / .

. - , , .

Entitfy Framerowk - 6.1.3 .Net 4.6, NuGet.

+4
1

, -, auto-property # 6.

"inline", Entity Framework .

, .

public class Company
{
    public virtual ICollection<BusinessUnit> BusinessUnits { get; protected set; }

    public int Id { get; protected set; }
}

public class BusinessUnit
{
    public virtual Company Company { get; protected set; }

    public int CompanyId { get; protected set; }

    public string Description { get; protected set; }
}
+3

Source: https://habr.com/ru/post/1622072/


All Articles