I've found that when using lazy child collections, the collection is loaded when an item is added directly to the context. This is a problem because the collection may be very large. I think EF wants to update the in memory collection with the new item, but it should realize that Í didn't request the collection.
One workaround is to make the property non virtual. Another is to make the parent class internal (WTF!?)
Here's code that reproduces the issue:
public class Country // make internal to avoid spurious select
{
public virtual int CountryID { get; set; }
public virtual ICollection<Citizen> Countries { get; set; } // make non virtual to avoid select
}
public class Citizen
{
public virtual int CitizenID { get; set; }
public virtual int CountryID { get; set; }
}
class Context : DbContext
{
public DbSet<Country> Countries { get; set; }
public DbSet<Citizen> Citizens { get; set; }
}
class Program
{
static void Main()
{
using (var db = new Context())
{
db.Countries.Add(new Country());
db.SaveChanges();
}
using (var db = new Context())
{
var c = db.Countries.FirstOrDefault();
db.Citizens.Add(new Citizen { CountryID = c.CountryID, }); // loads all citizens of the country
}
}
}
One workaround is to make the property non virtual. Another is to make the parent class internal (WTF!?)
Here's code that reproduces the issue:
public class Country // make internal to avoid spurious select
{
public virtual int CountryID { get; set; }
public virtual ICollection<Citizen> Countries { get; set; } // make non virtual to avoid select
}
public class Citizen
{
public virtual int CitizenID { get; set; }
public virtual int CountryID { get; set; }
}
class Context : DbContext
{
public DbSet<Country> Countries { get; set; }
public DbSet<Citizen> Citizens { get; set; }
}
class Program
{
static void Main()
{
using (var db = new Context())
{
db.Countries.Add(new Country());
db.SaveChanges();
}
using (var db = new Context())
{
var c = db.Countries.FirstOrDefault();
db.Citizens.Add(new Citizen { CountryID = c.CountryID, }); // loads all citizens of the country
}
}
}