gpt4 book ai didi

asp.net - LINQ to SQL - 如何选择特定列并返回强类型列表

转载 作者:行者123 更新时间:2023-12-03 07:01:11 25 4
gpt4 key购买 nike

我尝试使用 LINQ to SQL 从表中选择一些特定列,并将结果作为强类型对象列表返回。

例如:

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 class 是 LINQ to 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>在这里不影响任何东西(因为这是编译器所做的)。

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

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

请注意,在所有这些情况中,result静态类型(它的类型在编译时已知)。后一种类型是 List编译器生成的匿名类类似于 PersonInformation我上面写的类。从 C# 3.0 开始,该语言中没有动态类型。

更新:

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

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 - LINQ to SQL - 如何选择特定列并返回强类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1094931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com