开发者

ObservableCollection based on EF association does not get updated?

开发者 https://www.devze.com 2023-03-22 17:52 出处:网络
Here\'s a much simplified version of my code: Create the collection using the collection from the Entity Framework context:

Here's a much simplified version of my code:

Create the collection using the collection from the Entity Framework context:

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

Later on:

m = new Master(); //create master reco开发者_运维知识库rd
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();

This correctly sets the new Master record in the db.Masters; the new Master record in the 'masters' ObservableCollection; the Detail record in db.Details; but not the Detail records in the 'details' ObservableCollection?

I thought the ObservableCollection would be notified of these new records?


Hook an event to the CollectionChanged then you will need to see if a Detail has been added if it has then you will need to update the details collection yourself.

Update :

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.
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消