2011-01-07 83 views
1

对于这个愚蠢的问题感到抱歉,但这是我对WPF和Entity Framework的第一种方法。使用EntityFramework更新WPF ObservableCollection中的主 - 细部项目

让我们来解释一下我的情况......

我有一个主类(客户)和细节类(订单),无论是在我的EF上下文。 我使用LINQ-to-EF查询(包括Orders)加载我的主类,并将IEnumerable结果集放入ObservableCollection中,该列被用作ListBox的源。

然后我有一个DataGrid在哪里加载订单。 现在,由于主项目位于ObservableCollection中,因此我可以添加,删除和更新项目,并自动反映到我的ListBox。 问题是我需要向客户添加订单。

有没有办法只更新ObservableCollection中的一个项目,而无需重新加载上下文中的所有项目?

这是我的代码(简化)

// 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.ID, Item = "xxx"}; 
context.AddToOrders(o); 

// How can I update the ObservableCollection? 

在此先感谢,问题的

曼努埃尔

回答

0

部分可以手动设置关联(外键)财产上的订单。当添加的目的是在EF父对象,你真的只是做类似如下:

Order o = new Order {Item="xxx"}; 
c.Orders.Add(o); 
context.AddToOrders(o); 

通过这种方式创建对象,将其添加到集合上你想要的本地端(背后场景EF跟踪它的创建并记住给它一个Key和Association Key),并将它添加到上下文中的所有Orders集合中。

确保在完成该操作时调用保存更改,它将创建FK值并将其全部保存到数据库中。另外,注意:如果你有更详尽的对象层次结构thyan只是两个类,(很可能),如果你不想真正愚蠢地包含硬编码到你的代码中的语句,你可能会查看LazyLoading。这只会在实际请求时才会检索所需的数据,并会使您的LINQ语句更加简洁。

+0

感谢您的回答!这样,我只需向我的客户添加订单,但不会刷新我的ObservableCollection。 – Flea777 2011-01-08 12:18:45

相关问题