实体框架显式加载示例

时间:2013-02-23 11:54:13

标签: entity-framework-4 explicit

我在“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().)

        }
    }

2 个答案:

答案 0 :(得分:6)

该例外包含您需要做的事情:

  

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

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

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

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

答案 1 :(得分: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();