I want to databind my DataGridView control to database through Entity model (created with model first approach), i am using EF 5.0, .NET 4.5 and winforms
My binding is organized as follows:
DataGridView->BindingSource->BindingList->EF.DbSet->Database
The result (problem) is
1) updates to existing records are working properly
2) inserts are sent up to BindingList, but they ARE NOT sent to EF.DbSet
What could be the cause for this and how can I solve this?
My code:
//form level objects
private BindingList<Person> persons;
private BindingSource pSource=new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
_context=new TestEFmodelContainer();
var p = _context.PersonSet.ToList();
persons = new BindingList<Person>(p); //getting bindinglist
persons.AllowEdit = true;
persons.AllowNew = true;
pSource.DataSource = persons;
pSource.AllowNew = true;
personDataGridView.DataSource = pSource;
}
//"Save changes to DB" button
private void SaveChangesToDB_Click(object sender, EventArgs e)
{
_context.SaveChanges();
}
I finally managed to solve this!
Instead of these lines:
persons = new BindingList<Person>(p); //getting bindinglist
...
pSource.DataSource = persons;
i use this line:
pSource.DataSource = _context.Persons.Local.ToBindingList();
Where Persons is a DbSet<> from my DbContext
And one more thing that that i couldn't figure out was trying to make this work with derived EF model classes - let's say i have a BasePerson class and DerivedPerson class. EF creates DbSet only for BasePerson (that includes all derived instances, that are accessible through OfType method) I couldn't get to work .Local.ToBindingList for these derived classes.
The trick for the derived classes was to add DbSet for those Derived classes in DbContext class!