I am using Entity Framework with Code First to persist my data.
There is a class with a nested list:
public class AgeGroup
{
public BindingList<WeightGroup> WeightGroups { get; set; }
}
The database context consists of
public DbSet<AgeGroup> AgeGroups { get; set; }
I am creating a window, where the user can modify AgeGroups and their according WeightGroups. In order to bind a ListBox's ItemsSource property to the AgeGroups, I load them and bind to the Local set:
ctx.AgeGroups.Load();
vm.AgeGroups = ctx.AgeGroups.Local;
Up to here, the WeightGroups are not loaded, because they are not needed. So far, so good.
When the user chooses an AgeGroup for modification, its WeightGroups have to be loaded. Up to now I do it like this (in the setter of the SelectedAgeGroup property):
value.WeightGroups = (from age in ctx.AgeGroups
where age.Id == value.Id
select age.WeightGroups).Single();
However, this seems a bit clumsy. First of all, because a new list is set instead of filling the existing one. Furthermore, there are some behaviours, which are unwanted. This includes e.g. the following:
- If a
WeightGroupis modified andSaveChanges()is called, the old group is still there and additionally a new one with the modified values. - If the user removes an entity with
SelectedAgeGroup.WeightGroups.Remove(...)andSaveChanges(), the deleted rows are still there.
I assume, the reload of weight groups as listed above is causing this.
How would correct Lazy Loading look like in this case? Ideally, the necessary WeightGroups are loaded automatically by the framework. I read about using an IQueryable instead of BindingList for the WeightGroups property. But this interface does not have methods for inserting and removing entities. Furthermore, if I just exchange the types, not even the AgeGroups are loaded at all.