Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 "HasRequired" and "WithMany" partially working - not working as expected

So after going crazy for 3 hours and looking everywhere on the web I forced myself to ask here. I have been using Entity Framework for more than 5 years and I never had the kind of problem that I describe 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 query the 2 entities through their DbSets
  • Accessing the N to 1 "Company" navigation property on my "BusinessUnit" retrieved entity

The following does not work:

  • The 1 to N "BusinessUnits" navigation property on the retrieved "Company" entity is always NULL, even if using "Include" to do eager loading

What I am already doing that, according to EF guides and my experience, is correct:

  • Lazy loading is enabled (the 1 navigation works indeed)
  • Proxies are enabled (same as above)
  • The ICollection is virtual so lazy loading is enabled for it
  • The "HasRequired" part of the mapping is working, I can access the "Company" proxy on the "BusinessUnit" entity

I have tried changing the property setters to public, but still does not work/fix the problem

This has no apparent reason to misbehave. I am clearly missing something but I can't figure out what.

Entitfy Framerowk version in use is 6.1.3 on .Net 4.6, installed through NuGet package.

like image 564
Matteo Mosca Avatar asked Sep 25 '22 19:09

Matteo Mosca


1 Answers

The problem seems to be caused by the new initializers for auto-property feature of C# 6.

If you initialize the properties "inline" Entity Framework breaks on one to many relationships.

Remove the initializers and the navigation properties should work again.

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; }
}
like image 185
Albireo Avatar answered Oct 08 '22 21:10

Albireo