有没有办法确定何时将实际项目添加到ICollection<>从查询加载虚拟成员?
希望下面的代码能够证明我的观点!!
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;
}
}
}
和
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; }
}
加载这些的代码是
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();
在每个项目的DbAppointment ICollection ExceptionOcurrences设置器中,我需要执行一些附加逻辑。我遇到的问题是,一旦已经创建了DbAppointment对象,我似乎只有这些信息。
有没有办法确定何时添加了这些项目,以便我可以执行我的逻辑。
干杯 ABS
答案 0 :(得分:2)
显然,您所看到的行为意味着Entity Framework会创建并填充与此类似的集合:
// setter called with empty collection
dbAppointment.ExceptionOcurrences = new HashSet<DbExceptionOcurrence>();
// only getter gets called now
dbAppointment.ExceptionOcurrences.Add(dbExceptionOcurrence1);
dbAppointment.ExceptionOcurrences.Add(dbExceptionOcurrence2);
dbAppointment.ExceptionOcurrences.Add(dbExceptionOcurrence3);
//...
我曾希望您可以使用ObjectMaterialized Event(可以在此示例中注册DbContext
:https://stackoverflow.com/a/4765989/270591,EventArgs包含实体化实体)但不幸的是文档说:
在所有标量,复杂和引用之后引发此事件 属性已在对象上设置,但在集合之前 装载强>
看起来你必须在完成加载后运行结果集合,并在每个结果项上调用一些方法,在导航集上执行自定义逻辑。
也许另一种选择是创建一个自定义集合类型,它使用ICollection<T>
方法的事件处理程序实现Add
,并允许您在每次添加新项时挂钩某些逻辑。模型类中的导航集合必须属于该类型。甚至ObservableCollection<T>
甚至可以用于此目的。