3

我正在“northwind”数据库上尝试这部分代码。但是我收到了 DataBind 错误

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

        }
    }
4

2 回答 2

6

异常包含您需要做的事情:

...而是用数据填充 DbSet ...

所以你需要评估查询。例外提到了Load方法,但是因为无论如何您都需要在本地存储结果,所以最简单的解决方案是ToArray()在将查询分配给grdEmployees.DataSource.

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

ToArray方法将执行查询并在数组中返回结果集。

于 2013-02-23T13:03:14.777 回答
0

如果你想要记录组。

你应该使用.Tolist();

如 :

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

为了在获得一条记录时获得更好的结果,最好使用这个例子,因为它有更好的性能。如 :

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

对于带有分页的记录列表:

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();
于 2013-07-22T22:19:20.467 回答