sorry for the silly question but this is my first approach with WPF and Entity Framework.
Let's explain my scenario...
I have a master class (Customers) and a detail class (Orders), both in my EF context. I load my master class with a LINQ-to-EF query (including Orders) and put the IEnumerable result set in an ObservableCollection, that is used as source to a ListBox.
Then I have a DataGrid where I load the orders. Now, because the master items are in an ObservableCollection, I am able to add, delete and update an item and that automatically reflects to my ListBox. The problem is when I need to add an Order to a Customer.
Is there a way to update only an item in the ObservableCollection without re-load all the items from the context?
This is my code (simplified)
// Loading Customers
EntitiesContext context = new EntitiesContext();
IEnumerable<Customer> customers = from c in context.Customer.Include("Orders")
select c;
ObservableCollection<Customer> oc = new ObservableCollection<Customer>(customers);
// Binding ListBox
listCustomers.ItemsSource = oc;
...
// Retrieving a Customer (1st for instance...)
Customer c = (listCustomers.Items[0] as Customer);
Order o = new Order {Customer = c.I开发者_StackOverflowD, Item = "xxx"};
context.AddToOrders(o);
// How can I update the ObservableCollection?
Thanks in advance,
Manuel
Part of the problem may be manually setting the association (Foreign Key) property on the Order. When adding an object to a parent object in EF, you really just do something like the following:
Order o = new Order {Item="xxx"};
c.Orders.Add(o);
context.AddToOrders(o);
In this way you create the object, add it to the collection on the local side that you want it (behind the scenes EF tracks it's creation and remembers to give it a Key and Association Key) and it adds it to the contexts over-all Orders collection.
Be sure to call save changes when you are done with that operation and it will create the FK value and save it all to the database.
Also, of note: If you have more elaborate Object Hierarchies thyan just the two classes, (which is likely) you might look into LazyLoading if you don't want to have really goofy include statements hardwired into your code. This will retrieve needed data only when it is actually requested and will keep your LINQ statements a lot more succinct.
精彩评论