gpt4 book ai didi

entity-framework - EF 4.3(代码优先)- 确定何时将项目添加到虚拟 ICollection 属性

转载 作者:行者123 更新时间:2023-12-02 02:15:00 25 4
gpt4 key购买 nike

在从查询加载时,是否有任何方法可以确定何时将实际项目添加到 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 对象后才能获得此信息。

有什么方法可以确定项目何时添加,以便我可以执行我的逻辑。

干杯腹肌

最佳答案

显然,您所看到的行为意味着 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 包含物化实体)但不幸的是文档说:

This event is raised after all scalar, complex, and reference properties have been set on an object, but before collections are loaded.

看起来您必须在结果集合完全加载后运行它并在每个结果项上调用一些方法,这些方法在导航集合上执行您的自定义逻辑。

也许另一种选择是创建一个实现 ICollection<T> 的自定义集合类型使用 Add 的事件处理程序方法并允许您在每次添加新项目时挂接一些逻辑。您在模型类中的导航集合必须是该类型。甚至可能ObservableCollection<T>非常适合这个目的。

关于entity-framework - EF 4.3(代码优先)- 确定何时将项目添加到虚拟 ICollection 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com