不支持直接绑定到商店查询(DbSet、DbQuery、DbSqlQuery)的数据 [英] Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported

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

问题描述

我在 visual studio 2012 上编码并使用 实体模型 作为我的数据层.但是,当页面尝试加载时,我使用 Linq 语句的下拉控件往往会引发未处理的异常(上述标题).下面是我的代码;

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. 我想知道为什么会出现这个错误
  2. 使用 LINQ 时绑定到控件的正确方法是什么?

推荐答案

错误很明显——你不能直接绑定到查询结果,而是需要填充一些本地集合.

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

最简单的方法是通过ToList()将其转换为List:

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天全站免登陆