Question

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().)

        }
    }
Was it helpful?

Solution

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.

OTHER TIPS

If u want groups of record.

you should use .Tolist();

such as :

var states = (from s in yourentity.nameTbl
              select s).ToList();

to have better results in get one records, its better use this example because have better performance. such as :

var users = (from s in yourentity.UserTbls
             where s.User == Page.User.Identity.Name
             select s
            ).FirstOrDefault();

For list of record with paging:

int page = 1; // set your page number here
var rooms = (from s in yourentity.yourtable
             where s.User == Page.User.Identity.Name
             orderby s.Id descending
             select new {s.Id,s.Name,s.User}
            ).Skip((page-1)*SetPageSize).Take(SetPageSize).ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top