如何在不需要Linq中的新类型的情况下从表中获取列的子集
本文关键字:情况下 子集 获取 类型 不需要 Linq 新类型 | 更新日期: 2023-09-27 18:02:44
例如,如果我有以下类:
public class Schema
{
public int SchemaId { get; set; }
public byte[] XsdFile { get; set; }
public byte[] MetadataFile { get; set; }
public byte[] TemplateFile { get; set; }
public string Name { get; set; }
}
我在Linq中使用这个查询,我会得到所有的列:
from s in db.Schemas select s;
如果我只需要Id
和Name
列以及其他三字节数组字段的默认值,我将需要将其投影到另一个定义的类型或匿名类型或字典中,如下所示:
db.Schemas.ToDictionary(s => s.SchemaId, s => s.Name);
但是,我如何通过LINQ查询获得相同的类型,即Schema
本身,该查询将具有这些字节数组的默认值,而不是从表中获取它们?我真的不想创建另一个类型,也不能使用匿名类型,因为我想从web服务传输它。
将相关片段选择为匿名类型,调用.ToList()
将数据带入内存,然后投影到新的Schema对象中。
var result = (from s in db.Schemas
select new { s.SchemaId, s.Name })
.ToList()
.Select(s => new Schema
{
SchemaId = s.SchemaId,
Name = s.Name,
XsdFile = new byte[length],
MetadataFile = new byte[length],
TemplateFile = new byte[length]
});
将例程一分为二。
首先使用匿名型
var tempList= (from s in db.Schemas select new { s.SchemaId , s.Name}).ToList();
然后使用临时列表创建对象o类型Schema
var results = (from s in tempList
select new Schema { Schema = s.SchemaId , Name = s.Name }
).ToList();