gpt4 book ai didi

c# - 使用 WPF 和 Entity Framework 将查询绑定(bind)到数据网格

转载 作者:行者123 更新时间:2023-11-30 21:53:18 26 4
gpt4 key购买 nike

好的,所以我有一个 wpf 中的数据网格,我想使用 Entity Framework 将其绑定(bind)到 linq 查询的结果。例如,假设我有一个产品列表并且我只想显示打折产品:

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

但问题是:我还希望能够直接在数据 GridView 中添加/编辑销售产品,并将更改保存到数据库中。我该怎么做呢?

提前致谢。

最佳答案

将查询绑定(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 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.

现在将更改保存到您的 DataGrid ,您唯一需要做的就是创建一个方法或一个 command那个电话 SaveChanges你的上下文的方法:

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

关于c# - 使用 WPF 和 Entity Framework 将查询绑定(bind)到数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com