Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Explicit Loading Example

I'm trying this part of codes on "northwind" database.However I'm getting DataBind error

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            GetSpecificCustomer();
        }
    }

    private void GetSpecificCustomer()
    {
        using (var ctx = new northwindContext())
        {
            var query = ctx.Customers.Include("CustomerID").Take(3);

            grdEmployees.DataSource = query;
            grdEmployees.DataBind(); =>NotSupportedException was unhandled by user code(Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) 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().)

        }
    }
like image 446
Ahmet Güzel Avatar asked Sep 02 '26 00:09

Ahmet Güzel


1 Answers

The exception contains what you need to do:

...Instead populate a DbSet with data ...

So you need to evaluate the query. The exception mention the Load method but because you anyway need to store the result locally the easiest solution is to to call ToArray() on your query when assign it to grdEmployees.DataSource.

var query = ctx.Customers.Include("CustomerID").Take(3);
grdEmployees.DataSource = query.ToArray();
grdEmployees.DataBind();

The ToArray method will execute the query the returns the result set in an array.

like image 93
nemesv Avatar answered Sep 04 '26 21:09

nemesv