EF 4.3(代码优先) - 确定当项目被添加到虚拟ICollection的属性(EF 4.3 (C

2019-09-18 04:46发布

有任何方法来确定何时实际项目被添加到当正从查询装载它的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二传手的每个项目我需要执行一些addtional逻辑。 我遇到的问题是,我似乎只是这些信息一旦DbAppointment对象已经被创建。

有没有什么办法,以确定该项目已被添加,所以我可以执行我的逻辑。

干杯阿布斯

Answer 1:

显然,您所看到的行为意味着实体框架创建和填充类似这样的集合:

// 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事件 (可以用注册DbContext就像这个例子: https://stackoverflow.com/a/4765989/270591 ,EventArgs的含有物化实体)可惜文件说:

此事件后,所有标量,复杂的提高,以及参考属性已在对象上设置, 但加载集合之前

看起来,你必须通过结果集合已经完全加载后运行,并呼吁其在导航集进行自定义逻辑每个结果项目的一些方法。

也许另一种选择是创建一个实现自定义集合类型ICollection<T>与该事件处理程序Add方法,并允许你在一些逻辑每次一个新项目添加挂钩。 您的导航集合中的模型类必须是此类型。 甚至ObservableCollection<T>是细用于此目的。



文章来源: EF 4.3 (Code First) - determine when items are added to the virtual ICollection property