How to Link DataSource to DataGridView or ListView

advertisements

I am using the three layered architecture with Entity Framework 6.1 Code-First

Code in UI Layer

dataGridView1.DataSource = _userBLL.GetUsers();

Code in Business Logic Layer

public object GetUsers()
{
    return _userDAL.GetUsers();
}

Code in Data Access Layer

public object GetUsers()
{
    return db.Users.Select(u => u);
}

I can retrieve the data but while assigning the DataSource to DataGridView throwing below error:

Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList(). For ASP.NET WebForms you can bind to the result of calling ToList() on the query or use Model Binding, for more information see http://go.microsoft.com/fwlink/?LinkId=389592.

Can anyone help me with this error? How can I assign a retrieved data source to a DataGridView as well as to a ListView?


Call the ToList() method. Like this:

public object GetUsers()
{
   return db.Users.ToList();
}

Also you can use AsQueryable() like this: (Returning IQueryable<T> will defer execution of the query until its results are actually used.)

public IQueryable<User> GetUsers()
{
   return db.Users.AsQueryable();
}

Read this post may be useful: Why use AsQueryable() instead of List()