好的,所以我拥有的是 wpf 中的数据网格,我想将其绑定(bind)到使用 Entity Framework 的 linq 查询的结果。例如,假设我有一个产品列表,并且我只想显示特价产品:
var itemsOnSale = from item in context.products
where item.onSale == true
select item;
context.products.Load();
productViewSource.Source = itemsOnSale.ToList();
但问题是:我还希望能够直接在 datagridview 中添加/编辑正在销售的产品并将更改保存到数据库。我该如何去做呢?
提前致谢。
最佳答案
将查询绑定(bind)到 DataGrid
的最佳方式之一正在执行以下操作:
var itemsOnSale = from item in context.products
where item.onSale == true
select item;
itemsOnSale.Load();
productViewSource.Source=context.products.Local;
从此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.
现在将更改保存到您的 DataGrid
上,您唯一需要做的就是创建一个方法或 command那个电话SaveChanges
您的上下文的方法:
private void SaveProductChanges()
{
context.SaveChanges();
}
关于c# - 使用 WPF 和 Entity Framework 将查询绑定(bind)到数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990115/