当从查询加载 ICollection 虚拟成员时,有什么方法可以确定实际项目何时添加到 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;
}
}
}
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; }
}
加载这些的代码是
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);
//...
我本来希望你能使用对象物化事件 http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.objectmaterialized.aspx(可以注册DbContext
就像这个例子一样:https://stackoverflow.com/a/4765989/270591 https://stackoverflow.com/a/4765989/270591,EventArgs 包含物化实体)但不幸的是文档说:
在所有标量、复数和引用之后引发此事件
已在对象上设置属性,但在收集之前
已加载.
看来您必须在完全加载结果集合后运行它,并在每个结果项上调用一些方法,以在导航集合上执行自定义逻辑。
也许另一个选择是创建一个自定义集合类型来实现ICollection<T>
与一个事件处理程序Add
方法,并允许您在每次添加新项目时挂钩一些逻辑。模型类中的导航集合必须是该类型。甚至会ObservableCollection<T>
适合这个目的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)