直接将数据绑定到一个存储查询(DbSet,的DBQuery,DbSqlQuery)不支持 [英] Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported

查看:2145
本文介绍了直接将数据绑定到一个存储查询(DbSet,的DBQuery,DbSqlQuery)不支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编码的的Visual Studio 2012 并使用实体模型我的数据层。但是,我的下拉与Linq的语句的控制往往当网页尝试加载(声明以上职称)抛出未处理的异常。这里是我的code以下;

 使用(AdventureWorksEntities DW =新AdventureWorksEntities())
        {
            ddlCon.DataSource =(从时间在dw.Employees
                                 选择新的{em.Title,em.EmployeeID});            ddlCon.DataTextField =标题;
            ddlCon.DataValueField =雇员;
            ddlCon.DataBind();
            ddlCon.Items.Insert(0,新的ListItem( - 选择---, - 选择 - ));
        }


  1. 我想知道为什么发生这个错误

  2. 我应该使用LINQ时要绑定到一个控制的正确方法?


解决方案

该错误是相当明确的 - 你不能直接绑定到查询结果,但需要填充一些当地的集合,而不是

要做到这一点,最简单的方法是将其转换为列表< T> ,通过了ToList()

  ddlCon.DataSource =(从时间在dw.Employees
                             选择新的{em.Title,em.EmployeeID})了ToList()。

Am coding on visual studio 2012 and using Entity Model as my Data layer. However, my drop down control with the Linq statement tend to throw an unhandled exception when the page tries to load (stated title above). Here is my code below;

using (AdventureWorksEntities dw = new AdventureWorksEntities())
        {
            ddlCon.DataSource = (from em in dw.Employees
                                 select new { em.Title, em.EmployeeID });

            ddlCon.DataTextField = "Title";
            ddlCon.DataValueField = "EmployeeID";
            ddlCon.DataBind();
            ddlCon.Items.Insert(0, new ListItem("--Select--", "--Select--"));
        }

  1. I want to know why that error occurred
  2. What should be the proper way to bind to a control when using LINQ?

解决方案

The error is fairly clear - you can't bind directly to the query results, but need to populate some local collection instead.

The simplest way to do this is to convert it to a List<T>, via ToList():

 ddlCon.DataSource = (from em in dw.Employees
                             select new { em.Title, em.EmployeeID }).ToList();

这篇关于直接将数据绑定到一个存储查询(DbSet,的DBQuery,DbSqlQuery)不支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆