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

标签 c# wpf entity-framework linq datagrid

好的,所以我拥有的是 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 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/

相关文章:

wpf - 本地 WPF C# 编程

linq - 如何使用 Linq 连接对象和实体?

c# - 处理 DbContext 创建异常

c# - Entity Framework - 加载带有子实体的实体

javascript - JavaScript 中文本框最小长度验证

c# - 重定向到 ASP.NET MVC 中的操作,方法不会返回 View

c# - 将列表框绑定(bind)到 WPF 中字符串类型的 Observable 集合

具有右对齐值的 WPF TreeView

c# - 如何 "Build"包含所有资源文件(例如图片)的 exe? exe可以放到网页上吗?

c# - 类继承与多态——绘制简单形状