Reputation: 11184
Using c#, net.4.5 vs 2012
I'm trying to get data from database using Entity Framework.
At first idea was use code like below - it's must allow to add, delete and update entries in dataGridView, and than just save changes using context.SaveChanges()
(method from ObjectSet
, if I'm not wrong)
using (LibraryEntities context = new LibraryEntities())
{
var query = (from c in context.Book select c).First();
DataGridView dgv = new DataGridView();
dgv.DataSource = context.Book;
}
Result - exception
Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported...
Then I try a little bit changed code:
using (LibraryEntities context = new LibraryEntities())
{
var query = (from c in context.Book select c).First();
DataGridView dgv = new DataGridView();
dgv.DataSource = query;
}
but have same issue with exception
Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported...
At last try to convert all to List()
:
using (LibraryLib.LibraryEntities context = new LibraryLib.LibraryEntities())
{
DataGridView dgv = new DataGridView();
dgv.DataSource = (from c in context.Book select c).ToList();
}
As and expected, I got all db entries in DataGridView, but I can't add, update and delete any entries.
And the question is - how can I change db in dataGridView
and than save it with DbContext.SaveChanges()
Upvotes: 0
Views: 16884
Reputation: 84
I would suggest to use repository pattern with unitofwork pattern which means a repository class which will handle all CRUD operations and unit of work class to commit all the changes together.
Upvotes: 0
Reputation: 531
Is it winforms? if yes, you have to use BindingSource to link data
BindingSource bs = new BindingSource();
bs.DataSource = typeof(Book); // Book is a type of your Entity class
db.Book.ToList().ForEach(n => bs.Add(n));
dgv.DataSource = bs;
now it's editable. And to store changes just call db.SaveChanges();
your way to assing List to DataGrid is valid for WPF. What about to migrate there?
Upvotes: 2