【问题标题】:Entity Framework 4.4, reloading Child collection objectsEntity Framework 4.4,重新加载子集合对象
【发布时间】:2013-06-25 10:32:44
【问题描述】:

我已经搜索了一段时间,但找不到任何作品。我有两个对象的情况(见下面的定义)。子对象是父对象的集合。我正在使用 WPF/Prism 和 Entity Framework 4.4 在 Visual Studio 2012 中工作

class Parent
{
    ...other properties...
    public virtual ICollection<Child> Children { get; set; }
} 

class Child
{
    public string Value1 { get; set }
    public string Value2 { get; set }
    public string Value3 { get; set }
}

我有一个表单,它的父项加载到左侧的列表框中,用户单击列表中的一项,我们在右侧显示属性。一切都很好,直到我们有两台机器访问同一个数据库。如果一台机器添加或更新其中一条记录,我在第二台机器获取数据时遇到问题...

我有以下代码可以尝试修复它,但似乎在实体框架中应该有一个简单的方法。

DbEntityEntry<Parent> entry = dbContext.Entry(parent);
entry.Reload(); //Note: this refreshes the properties on the Parent object (but not the collection

if (Parent.Children != null)
{
   Array a = doc.Children.ToArray<Child>();  //this is here because they may have deleted one of the records 

   foreach (Child g in a)
   {
       DbEntityEntry<Child> c= dbContext.Entry(g);
       c.Reload();  //Note: if it is deleted, the Parent.Child gets updated automatically to remove the record.
   }
}

entry.Collection(o => o.Children ).Load(); //call this to get new records

我有什么想法我可以做得更好,或者这是这样做的方式吗?????

【问题讨论】:

  • +1 因为我发现它是一个很好的解决方案(我了解到Reload 会从子集合中删除已删除的实体)。我怀疑您是否可以将其压缩成一个简单的单线左右。使用 EF 更新/刷新对象图并不容易。
  • 我的解决方案遇到的一个问题是,在我的实际代码中,我有 4-5 个这些类型的集合。似乎第一次重新加载也应该重新加载所有子集合,或者至少 ntry.Collection(o => o.Children ).Load();也许应该有一个“重新加载”
  • 找到了一种更好的方法来在数组((IObjectContextAdapter)dbContext).ObjectContext.Refresh(RefreshMode.StoreWins, parent.Children); 上执行上述 foreach,这将删除条目并更新当前条目。仍然需要 .Load() 来获取新记录。这似乎也快了很多。

标签: caching entity-framework-4 parent-child parent reload


【解决方案1】:

将此移至答案

找到了一种更好的方法来在数组上执行上述“foreach”

((IObjectContextAdapter)dbContext).ObjectContext.Refresh(RefreshMode.StoreWins, parent.Children); 

这会删除条目并更新当前条目。仍然需要 .Load() 来获取新记录。这似乎也快了很多

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2013-01-22
    • 2017-07-13
    • 2021-11-06
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多