我试图使用LINQ to SQL从表中 Select 几个特定的列,并将结果作为强类型对象列表返回.

例如:

var result = (from a in DataContext.Persons
                              where a.Age > 18
                              select new Person
                              {
                                  Name = a.Name,
                                  Age = a.Age
                              }
                              ).ToList();

任何帮助都将不胜感激.

它构建得很好,但是当我运行它时,我得到了错误.不允许在查询中显式构造实体类型MyEntity.

推荐答案

基本上,你做这件事的方式是正确的.但是,您应该使用DataContext的实例进行查询(DataContext是否为您查询中的实例或类型名称并不明显):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

显然,Person类是LINQ到SQL生成的实体类.如果您只需要一些列,那么应该创建自己的类:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

在这里,你可以自由地将varList<PersonInformation>交换,而不影响任何事情(compiler就是这样做的).

否则,如果您在本地处理查询,我建议您考虑使用匿名类型:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

注意in all of these casesresultstatically typed(它的类型在编译时是已知的).后一种类型是编译器生成的匿名类的List,类似于我上面写的PersonInformation类.从C#3.0开始,该语言中没有动态输入.

更新:

如果你真的想退回List<Person>(这可能是最好的 Select ,也可能不是),你可以这样做:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

你也可以合并上面的陈述,但为了清晰起见,我把它们分开了.

Asp.net相关问答推荐

Razor页面上@Foreach的正确语法,其中值可以等于多个值

如何格式化搜索字符串以从 Razor 页表中的多个列返回部分搜索字符串?

.Net Framework:w3wp.exe 中的异常

web.config 部分的单独配置文件

在 Sessions 中存储自定义对象

MSCharts找不到请求类型'GET'的http处理程序错误

是否可以使用 Membership API 更改用户名

如何使用 javascript 获取 MVC 应用程序的基本 URL

在 RedirectToAction 调用中传播 QueryString 参数

使用 JavaScript 禁用 ASP.NET 验证器

问题映射 HttpHandler --> HTTP Error 404 Not Found

ASP.Net:在共享/静态函数中使用 System.Web.UI.Control.ResolveUrl()

当用户使表单无效时单击取消按钮时,如何清除 MVC 客户端验证错误?

在 asp.net 中将 JSON 转换为 .Net 对象时出错

如何获得 System.Diagnostics.Process 的输出?

如何获取当前登录用户的角色列表

MVC3 值 Ajax 文件上传

在 C# 中动态创建 Json

将 HTML 字符串转换为图像

在 ASP.NET 中使用 SecureString 有什么好处吗?