I’m using entity framework 5.
I’m trying to lazy load an entity collection, I stripped the model to the bare bones to have a simple runable sample.
This is my model:
public class A
{
public int Id { get; set; }
public EntityCollection<B> Bs
{
get { return bs; }
set { bs = value; }
}
private EntityCollection<B> bs;
public A()
{
bs = new EntityCollection<B>();
}
}
public class B
{
public int Id { get; set; }
public A A { get; set; }
}
public class DbModel : DbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<A>()
.HasKey( t => t.Id )
.HasMany(a => a.Bs)
.WithRequired(b => b.A);
modelBuilder.Entity<A>()
.Property(t => t.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<B>()
.HasKey(b => b.Id)
.HasRequired(b => b.A);
modelBuilder.Entity<B>()
.Property( t => t.Id )
.HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
}
This is the test demonstrating my problem:
[TestInitialize]
public void Initialize()
{
model = new DbModel();
model.Configuration.ProxyCreationEnabled = false;
if (model.Database.Exists()) model.Database.Delete();
model.Database.Create();
A a = model.As.Create();
model.As.Add(a);
B b = model.Bs.Create();
a.Bs.Add(b);
model.ChangeTracker.DetectChanges();
model.SaveChanges();
}
[TestMethod]
public void TestMethod1()
{
// arrange
DbModel tModel = new DbModel();
A a = tModel.As.First();
// act
a.Bs.Load();
}
This is the result:
Test method TestProject1.UnitTest1.TestMethod1 threw exception:
System.InvalidOperationException: Requested operation is not allowed
when the owner of this RelatedEnd is null. RelatedEnd objects that
were created with the default constructor should only be used as a
container during serialization.
As it turns out I was using classes from different paradigms of the ADO family.
As pointed out by Gert Arnold EF doesn’t work with EntityCollection it uses a plain list for association collections.
As I did not want the proxies, the objects have no “knowledge” of the model. So the model itself has to be used to load associations for an entity.
For this sample I added the following method to the model:
I adapted the test to use the new method
It gives a green now