如何使用Entity Framework以DataGridView可编辑和上下文轨迹更改的方式过滤数据? [英] How to filter data using Entity Framework in a way that DataGridView be editable and context track changes?

查看:205
本文介绍了如何使用Entity Framework以DataGridView可编辑和上下文轨迹更改的方式过滤数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#Windows窗体应用程序使用实体框架(EFWinForms)使用以下代码填充来自sql server数据库表的数据:

I'm using C# Windows Form Application to populate data from sql server database table using Entity Framework (EFWinForms) using the following code :

MyEntityDataModel db = new MyEntityDataModel();
MyEDS = new EntityDataSource();
MyEDS.DbContext = db;
MyDataGridView.DataSource = MyEDS;
MyDataGridView.DataMember = "MyTable";

它工作正常。用户编辑时,添加数据;可以使用以下代码保存数据:

It works fine. When user edit,add data ; data can be saved using the following code :

MyEDS.SaveChanges();

我想要一种通过实体数据源筛选这些数据的方式,以便MyDataGridView保持可编辑,并完成任何更新由用户在过滤数据中仍然可以保存回数据库。
注意:当使用LINQ对实体过滤数据时,它工作得很好,但它只是填充了用户再次无法编辑或更新的数据的快照。

I want a way to filter these data throug Entity Data source so that MyDataGridView remains editable and any update done by user in filtered data can still be Saved back to database. Note: When using linq to entity to filter data it works great but it just populate a snapshot of data that can't be edited or updated by user again.

推荐答案

当您想在连接模式下使用Windows窗体中的实体框架时,应该考虑一些重点。然后,您可以正确保存更改。

There are some important points which you should consider when you want to work with entity framework in windows forms in connected mode. Then you can save changes properly.

使用DbContext的单个实例

使用您的 DbContext 的单个实例。如果在保存更改时创建新实例,则新实例将无法看到您在其他实例上所做的任何更改。所以在表单级别声明:

Use a single instance of your DbContext. If you create a new instance when saving changes, the new instance can't see any change that you made on other instance. So declare it at form level:

TestDBEntities db = new TestDBEntities();

加载数据 - 绑定到实体的本地存储

当您使用连接模式下的实体工作时,首先使用 db.Products.ToList()加载数据,然后绑定 BindingSource db.Products.Local.ToBindingList()

它将网格直接绑定到实体集。因此,如果您从绑定源添加或删除,更改跟踪器会检测更改,并为您添加和删除项目。您可以这样加载数据:

When you work with Entities in connected mode, first load data using db.Products.ToList() then bind your BindingSource to db.Products.Local.ToBindingList().
It binds the grid directly to the entity set. So if you add or remove from binding source, change tracker detects changes and adds and removes items for you. You can load data this way:

db.Configuration.ProxyCreationEnabled = false;
db.Products.ToList();
this.productBindingSource.DataSource = db.Products.Local.ToBindingList();

使用Linq过滤数据

要过滤数据,请使用linq。当基础列表为时,您不能使用 Filter 属性 BindingSource BindingList< T> / code>;只有实现 IBindingListView 接口支持过滤的底层列表。例如,您可以通过以下方式过滤数据:

To filter data, use linq. You can not use Filter property of BindingSource when the underlying list is BindingList<T>; Only underlying lists that implement the IBindingListView interface support filtering. For example you can filter data this way:

var filteredData = db.Products.Local
                     .Where(x => x.Name.Contains(this.FilterTextBox.Text));
this.productBindingSource.DataSource = filteredData;

删除过滤器

要删除过滤器,只需将绑定源的数据源再次设置为实体的本地存储。当您删除过滤器时,这样添加和删除将会起作用。

To remove filter, just set the data source of your binding source to the local storage of your entities again. This way adding and removing will work when you remove filter.

this.productBindingSource.DataSource = db.Products.Local.ToBindingList();

添加/删除/修改

添加将仅在未过滤的模式下工作。要让用户添加实体,请删除过滤器。你可以使它工作,但它是合理的,不要碰它。

Add will work only in unfiltered mode. To let the user add entities, remove filter. you can make it work but it's reasonable don't touch it.

编辑将在过滤或未过滤的模式下工作。

Editing will work in both filtered or unfiltered mode.

删除可以在已过滤或未过滤的模式下工作。但是如果您使用 BindingNavigator ,则不能依赖其删除按钮,您应该设置其 DeleteItem 否none和handle其删除项目单击事件并编写自己的代码:

Remove can work in both filtered or unfiltered mode. But if you use BindingNavigator you can't rely on its delete button and you should set its DeleteItem no none and handle its delete item click event and write your own code:

db.Products.Local.Remove((Product)this.productBindingSource.Current);
this.productBindingSource.RemoveCurrent(); 

示例代码

下面是一个包含上述内容的示例代码。

Below is a sample code which contains what I described above.

using System.Data.Entity;
//...

TestDBEntities db = new TestDBEntities();
private void Form1_Load(object sender, EventArgs e)
{
    db.Configuration.ProxyCreationEnabled = false;
    db.Products.ToList();
    this.productBindingSource.DataSource = db.Products.Local.ToBindingList();
}

private void FilterButton_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(this.FilterTextBox.Text))
    {
        this.productBindingSource.DataSource = db.Products.Local.ToBindingList();
    }
    else
    {
        var filteredData = db.Products.Local
                             .Where(x => x.Name.Contains(this.FilterTextBox.Text));
        this.productBindingSource.DataSource = filteredData;
    }
}

private void productBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
    db.SaveChanges();
}

private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
{
    db.Products.Local.Remove((Product)this.productBindingSource.Current);
    this.productBindingSource.RemoveCurrent();
}

这篇关于如何使用Entity Framework以DataGridView可编辑和上下文轨迹更改的方式过滤数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆