基于EF关联的ObservableCollection没有更新?

时间:2011-07-26 06:14:21

标签: c# entity-framework observablecollection

这是我的代码的简化版本:

使用Entity Framework上下文中的集合创建集合:

db = new MainEntities();
ObservableCollection<Master> masters = new ObservableCollection<Master>(db.Masters);
ObservableCollection<Detail> details = new ObservableCollection<Detail>(db.Details);

后来:

m = new Master(); //create master record
d = new Detail(); //create detail record
m.Details.Add(d); //attach the detail to the master entityobject
masters.Add(m); //add to the ObservableCollection
db.SaveChanges();

这正确地在db.Masters中设置新的Master记录; 'masters'ObservableCollection中的新Master记录; db.Details中的Detail记录;但不是'详细信息'ObservableCollection中的详细记录?

我以为ObservableCollection会收到这些新记录的通知吗?

1 个答案:

答案 0 :(得分:1)

将事件挂钩到CollectionChanged,然后您需要查看是否添加了详细信息,然后您需要自己更新详细信息收集。

更新:

masters.CollectionChanged += new NotifyCollectionChangedEventHandler(records_CollectionChanged);

void records_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//e.NewItems will be an IList of all the items that were added
//You will add then find the new details and add to details collection.
}