Entity Framework and DataNavigator
Has anyone managed to bind a DataNavigator and a DataGrid using the DataSource property and the ADO.NET Entity Framework so that add and delete (+ and - buttons in the data navigator). work? I have the problem, that everytime i click on the add button of the DataNavigator, the EntityState is always set to detached. I can't figure out, how to add this detached entity to the DataContext.
my code is simple (using a static session class and a partial class):
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)
开发者_StackOverflow社区{
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.
}
}
Help's appreciated!
-christian
I think you should use BindingSource
control instead of using DataSource
and handle AddingNew
event to manually set State to Added
by calling AddObject
.
DataGrid doesn't know anything about source of data so it cannot communicate with entity framework context / set and add object. You must do it manually and for that you need some event to handle when new record is added. I believe AddingNew
and BindingSource
is way to go.
精彩评论