【发布时间】:2013-09-24 19:39:05
【问题描述】:
我正在使用实体框架 5.0 + .NET 4.5
我使用 EF 模型优先方法创建了数据库,我想使用 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) 我添加了一个代码来添加新记录,其中包含用于单个记录属性(文本框、日期选择器)的一堆控件
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 派生自 UnifOfSales 和 UnitOfSales 派生自 BaseCategory 类。
我尝试的另一件事
我尝试了 Ladislav Mrnka 在这篇文章中建议的 (..).Local.ToBindingList How to make two way-databinding using EF in winforms?
它确实将更改发送回数据库,但更改仅存储在基类表 (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();
【问题讨论】:
-
你在某处调用 _context.SaveChanges 重载吗?
-
不,我不知道,据我了解,此方法来自 DbContext 类
标签: c# entity-framework data-binding