C# 实体框架和数据导航器
是否有人使用DataSource属性和ADO.NET实体框架绑定了DataNavigator和DataGrid,以便在data navigator中添加和删除(+和-按钮)。工作我有一个问题,每次单击DataNavigator的add按钮时,EntityState总是设置为Distached。我不知道如何将这个分离的实体添加到DataContext 我的代码很简单(使用静态会话类和分部类):C# 实体框架和数据导航器,c#,winforms,entity-framework,datagrid,C#,Winforms,Entity Framework,Datagrid,是否有人使用DataSource属性和ADO.NET实体框架绑定了DataNavigator和DataGrid,以便在data navigator中添加和删除(+和-按钮)。工作我有一个问题,每次单击DataNavigator的add按钮时,EntityState总是设置为Distached。我不知道如何将这个分离的实体添加到DataContext 我的代码很简单(使用静态会话类和分部类): 谢谢你的帮助 -christian我认为您应该使用BindingSource控件,而不是使用Data
谢谢你的帮助
-christian我认为您应该使用
BindingSource
控件,而不是使用DataSource
并通过调用AddObject
处理AddingNew
事件来手动将状态设置为Added
DataGrid对数据源一无所知,因此无法与实体框架上下文/集合和添加对象通信。您必须手动执行此操作,因此在添加新记录时需要处理一些事件。我相信AddingNew
和BindingSource
是一条路要走
internal class Session
{
private static Entities _entities;
public static Entities Entities
{
get { return _entities ?? (_entities = new Entities()); }
set { _entities = value; }
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitData();
}
private void InitData()
{
gridControl1.DataSource = Session.Entities.SomeObjects;
dataNavigator1.DataSource = Session.Entities.SomeObjects;
}
}
public partial class SomeObjects
{
public SomeObjects()
{
PropertyChanged += SomeObject_PropertyChanged;
ObjectId = Guid.NewGuid();
}
private void SomeObject_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Debug.WriteLine(EntityState); // when i change a existing record in the grid, EntityState is set to modified and can be saved easily using SaveChanges. But when i add a new entity, EntityState is always set to detached.
}
}