有没有办法确定从查询加载时何时将实际项添加到 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 setter 中,我需要执行一些额外的逻辑。我遇到的问题是,我似乎只有在创建了 DbAppointment 对象后才拥有此信息。
有没有办法确定何时添加了项目,以便我可以执行我的逻辑。
干杯腹肌
显然,您看到的行为意味着实体框架创建和填充集合,如下所示:
// 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 包含物化实体),但不幸的是文档说:
此事件在所有标量、复杂和引用之后引发 已在对象上设置属性,但在集合之前 加载。
看起来您必须在完全加载结果集合后运行结果集合,并在每个结果项上调用某个方法,该方法在导航集合上执行自定义逻辑。
也许另一种选择是创建一个自定义集合类型,该类型使用 Add
方法的事件处理程序实现ICollection<T>
,并允许您在每次添加新项时挂钩一些逻辑。模型类中的导航集合必须是该类型。也许甚至ObservableCollection<T>
也可以达到这个目的。