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:
The following does not work:
What I am already doing that, according to EF guides and my experience, is correct:
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.
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; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.