Is there any way to determine when actual items are added to an ICollection<> virtual member when it is being loaded from a query?
Hopefully the code below will be able to demonstrate my point!!
public class DbAppointment
{
public DbAppointment()
{
}
public virtual int AppointmentId { get; set; }
public virtual string Subject { get; set; }
public virtual string Body { get; set; }
public virtual DateTime Start { get; set; }
public virtual DateTime End { get; set; }
private ICollection<DbExceptionOcurrence> exceptionOcurrences;
public virtual ICollection<DbExceptionOcurrence> ExceptionOcurrences
{
get { return exceptionOcurrences; }
set
{
exceptionOcurrences = value;
}
}
}
and
public class DbExceptionOcurrence
{
public DbExceptionOcurrence()
{
}
public virtual int ExceptionId { get; set; }
public virtual int AppointmentId { get; set; }
public virtual DateTime ExceptionDate { get; set; }
public virtual DbAppointment DbAppointment { get; set; }
}
The code for loading these is
Database.SetInitializer(new ContextInitializer());
var db = new Context("EFCodeFirst");
// when this query executes the DbAppointment ExceptionOcurrenes (ICollection) is set
// but for some reason I only see this as an empty collection in the virtual setter DbAppointment
// once the query has completed I can see the ExceptionOcurrences
var result = db.Appointments.Include(a => a.ExceptionOcurrences).ToList();
In the DbAppointment ICollection ExceptionOcurrences setter for each item I need to perform some addtional logic. The problem I am having is that I only seem to have this information once the DbAppointment objects have already been created.
Is there any way to determine when the items have been added so I can perform my logic.
Cheers
Abs
Apparently the behaviour you are seeing means that Entity Framework creates and fills the collection similar to this:
I had hoped that you can use the ObjectMaterialized Event (can be registered with
DbContextlike in this example: https://stackoverflow.com/a/4765989/270591, the EventArgs contain the materialized entity) but unfortunately the documentation says:It looks that you have to run through the result collection after it has been loaded completely and call some method on each result item which performs your custom logic on the navigation collection.
Maybe another option is create a custom collection type that implements
ICollection<T>with an event handler for theAddmethod and allows you to hook in some logic everytime a new item is added. Your navigation collection in the model class would have to be of that type. Maybe evenObservableCollection<T>is fine for this purpose.