繁体   English   中英

将DataGridView绑定到具有EF5类的数据库,而不将更改发送到数据库

[英]Binding DataGridView to database with EF5 classes not sending changes to database

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

我已经使用EF Model first方法创建了数据库,并且希望使用EF类将DataGridView绑定到数据库,以便对数据库或DataGridView中的任何更改自动进行同步。

这是我的代码:

//form level fields
private BindingList<Product> _products;
private BindingSource _productSource = new BindingSource(); 

... in the form load event
//load the data from database using EF classes
var tmp = _context.BaseCategorySet.OfType<Product>().ToList();

//converting to IBindingList
_products = new BindingList<Product>(tmp);
_products.AllowEdit = true;
_products.AllowNew = true;

_productSource.DataSource = _products; 

//setting GridControl's data source
ProductGrid.DataSource = _productSource;

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

我为希望找到解决方案而做的其他事情...

1)我添加了一个保存按钮,以调用使用代码将网格控件的数据显式更新到数据库:

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

->这没有导致将新记录存储到数据库中

2)我添加了一个代码,以添加带有针对单个记录属性(文本框,DatePickers)的一堆控件的新记录

var x = _context.BaseCategorySet.Create<Product>();
//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切换到标准DataGridView控件,但这没有帮助...

我搜索了很多关于EF数据绑定的主题,但都没有成功...

不知道这个事情,但我用我的实体模型的产业, Product派生自UnifOfSalesUnitOfSales派生自BaseCategory类。

我尝试了另一件事

我尝试了Ladislav Mrnka在本文中建议的(..)。Local.ToBindingList 如何在 Winforms中使用EF进行两种方式数据绑定?

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

_context.BaseCategorySet.OfType<Product>.Load(); 
//i tried to use derived class with OfType<Product> 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(); 

我确实找到了解决方案!

我必须在EF模型派生类的DbContext类中添加DbSet产品(产品,派生自BaseCategory类)

之后,我可以使用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM