How to get data from database with Entity Framework?

.net c# datagridview entity-framework winforms

Question

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.

enter image description here

And the question is - how can I change db in dataGridView and than save it with DbContext.SaveChanges()

1
1
1/13/2014 9:39:18 PM

Accepted Answer

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?

2
1/13/2014 7:29:23 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow