user1572808
user1572808

Reputation: 41

Binding query to datagrid with WPF and Entity Framework

Ok, so what I have is a datagrid in wpf that I want to bind to the results of a linq query using the entity framework. For instance, lets say I have a list of products and I want to display only products on sale:

var itemsOnSale = from item in context.products 
       where item.onSale == true 
       select item;
context.products.Load();
productViewSource.Source = itemsOnSale.ToList();

But here's the catch: I also want to be able to add/edit the products on sale directly in the datagridview and save the changes to the database. How would I go about doing this?

Thanks in advance.

Upvotes: 2

Views: 3146

Answers (1)

ocuenca
ocuenca

Reputation: 39326

One of the best way to bound your query to your DataGrid is doing the following:

var itemsOnSale = from item in context.products 
       where item.onSale == true 
       select item;

itemsOnSale.Load();
productViewSource.Source=context.products.Local;

From this link:

Load is a new extension method on IQueryable that will cause the results of the query to be iterated, in EF this equates to materializing the results as objects and adding them to the DbContext in the Unchanged state

The Local property will give you an ObservableCollection<TEntity> that contains all Unchanged, Modified and Added objects that are currently tracked by the DbContext for the given DbSet. As new objects enter the DbSet (through queries, DbSet.Add/Attach, etc.) they will appear in the ObservableCollection. When an object is deleted from the DbSet it will also be removed from the ObservableCollection. Adding or Removing from the ObservableCollection will also perform the corresponding Add/Remove on the DbSet. Because WPF natively supports binding to an ObservableCollection there is no additional code required to have two way data binding with full support for WPF sorting, filtering etc.

Now to save that changes on your DataGrid, the only you need to do is create a method or a command that call SaveChanges method of your context:

private void SaveProductChanges()
{
   context.SaveChanges(); 
} 

Upvotes: 3

Related Questions