【问题标题】:Select a specific column in LINQ web service with Entity Framework使用实体框架选择 LINQ Web 服务中的特定列
【发布时间】:2016-12-29 04:46:29
【问题描述】:

我只想从包含列 ID、Name、Gender 和 MarkUp 的简单表中返回一个名为 Name 的列。

当我运行以下代码时,出现以下错误:

无法将类型“System.Collections.Generic.List”隐式转换为“System.Collection.Generic.List”

代码:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using SimpleWebApplication;
using System.Configuration;

namespace SimpleWebApplication
{
    /// <summary>
    /// Summary description for SimpleWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class SimpleWebService : System.Web.Services.WebService
    {


        [WebMethod]
        public List<tblStudent> getAllLINQ()
        {
            List<string> studentList = new List<string>();
            try
            {
                using (TestingEntities database = new TestingEntities())
                {
                    var studentData = (from table in database.tblStudents select table).Select(u => new { u.Name });
                    studentList = studentData.ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return studentList;
        }


    }
}

【问题讨论】:

  • 在 studentList = studentData.ToList() 处出错
  • 您能否编辑问题以从文件顶部显示带有 using 语句的块?

标签: c# entity-framework linq


【解决方案1】:

如果您只需要名称,则只需选择名称。

var query = from table in database.tblStudents select Name;

并且您的列表应该是string 的列表,因为名称是字符串。

List<string> studentList = new List<string>();

您可以像这样将结果分配给您的列表:

studentList = query.ToList();

【讨论】:

  • 那么怎么写在 studentList = studentData.toList() 这行还是报错。
  • 编码耀西。你是对的。有用。如果我想选择两列怎么办?
  • 只需在您的选择中添加更多列,如下所示:select Name, SomeOtherColumn, SomeOtherColumn2。但请记住,如果您选择多于 1 列,那么当您尝试将结果放入列表时,该列表不能是字符串列表,而是自定义类型的列表,并且该自定义类型需要具有相同的属性作为您选择的列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
相关资源
最近更新 更多