Reputation: 41
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
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 onIQueryable
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 theDbContext
in theUnchanged
stateThe
Local
property will give you anObservableCollection<TEntity>
that contains allUnchanged
,Modified
andAdded
objects that are currently tracked by theDbContext
for the givenDbSet
. As new objects enter theDbSet
(through queries,DbSet
.Add
/Attach
, etc.) they will appear in theObservableCollection
. When an object is deleted from the DbSet it will also be removed from theObservableCollection
. Adding or Removing from the ObservableCollection will also perform the correspondingAdd
/Remove
on theDbSet
. Because WPF natively supports binding to anObservableCollection
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