使用EF5类将DataGridView绑定到数据库而不将更改发送到数据库

我正在使用Entity Framework 5.0 + .NET 4.5

我使用EF Model第一种方法创建了数据库,我想使用EF类将DataGridView绑定到数据库,以便自动同步对数据库或DataGridView任何更改。

这是我的代码:

 //form level fields private BindingList _products; private BindingSource _productSource = new BindingSource(); ... in the form load event //load the data from database using EF classes var tmp = _context.BaseCategorySet.OfType().ToList(); //converting to IBindingList _products = new BindingList(tmp); _products.AllowEdit = true; _products.AllowNew = true; _productSource.DataSource = _products; //setting GridControl's data source ProductGrid.DataSource = _productSource; 

我可以添加新行或更改数据,但这些更改不会发送到数据库 – 我缺少什么?

我做的其他事情希望找到解决方案……

1)我添加了一个Save按钮来调用显式更新网格控件的数据到数据库,代码如下:

 _productSource.EndEdit(); _context.SaveChanges(); 

– >这不会导致将新记录存储到数据库中

2)我添加了一个代码来添加新记录,其中包含一组用于单个记录属性的控件(Textboxes,DatePickers)

 var x = _context.BaseCategorySet.Create(); //settting all the x properties with values //that are set in aforementioned individual controls _context.BaseCategorySet.Add(x); _context.SaveChanges(); 

– >当我使用这种技术添加新记录时 – 它存储在数据库中,但再次出现奇怪的行为 – 这个新记录不会自动加载到网格控件中(但应该是,因为我将网格数据绑定到相应的EF DbSet …)

还有一个奇怪之处 – 我在DataGridView控件中对加载到数据库的记录进行的更新 – 这些更新被发送到数据库……

3)我从DevExpress XtraGrid切换到XtraGrid DataGridView控件,但这没有帮助…

我搜索了大量有关EF数据绑定的主题但没有成功……

不知道这是否重要,但我在我的实体模型中使用inheritance: Product派生自UnifOfSalesUnitOfSales派生自BaseCategory类。

还有一件事我试过了

我试过Ladislav Mrnka在这篇文章中建议的(..)。Local.ToBindingList 如何在winforms中使用EF进行双向数据绑定?

它确实将更改发送回数据库,但更改仅存储在基类表(BaseCategory)中,但也有一个派生类的表。 这是我用于绑定的代码

 _context.BaseCategorySet.OfType.Load(); //i tried to use derived class with OfType to ensure that compiler //knows that this is instance of derived class (Product), //not the base class BaseCategory, //but I can not get "Local" working with OfType... ProductGridView.DataSource = _context.BaseCategorySet.Local.ToBindingList(); 

我确实找到了解决方案!

我必须在DbContext类中为EF模型派生类添加DbSet Products(Product,派生自BaseCategory类)

在此之后,我可以使用

 ProductGridView.DataSource=_context.Products.Local.ToBindingList();