C# 通过linq从表中选择两列
我使用下面的查询获取实体框架Linq中的所有列(20多个)。由于内存不足异常,我只想得到其中两个。一个是“文件名”,另一个是“文件路径”。如何修改我的代码C# 通过linq从表中选择两列,c#,linq,C#,Linq,我使用下面的查询获取实体框架Linq中的所有列(20多个)。由于内存不足异常,我只想得到其中两个。一个是“文件名”,另一个是“文件路径”。如何修改我的代码 var query = DBContext.Table1 .Where(c => c.FacilityID == facilityID && c.FilePath != null && c.TimeStationOffHook < oldDate) .OrderBy(c =>
var query = DBContext.Table1
.Where(c => c.FacilityID == facilityID && c.FilePath != null && c.TimeStationOffHook < oldDate)
.OrderBy(c => c.FilePath)
.Skip(1000)
.Take(1000)
.ToList();
foreach(var t in query)
{
Console.WriteLine(t.FilePath +"\\"+t.FileName);
}
var query=DBContext.Table1
.Where(c=>c.FacilityID==FacilityID&&c.FilePath!=null&&c.TimeStationOffHookc.FilePath)
.Skip(1000)
.取(1000)
.ToList();
foreach(查询中的var t)
{
Console.WriteLine(t.FilePath+“\\”+t.FileName);
}
var query=DBContext.Table1.Where(c=>c.FacilityID==FacilityID&&c.FilePath!=null&&c.TimeStationOffHookc.FilePath)
.Skip(1000)
.取(1000)
.Select(c=>new{c.FilePath,c.FileName})
.ToList();
foreach(查询中的var t)
{
Console.WriteLine(t.FilePath+“\\”+t.FileName);
}
您需要使用。只需从两列中选择:
DBContext.Table1.Select(c => new { c.FileName, c.FilePath });
像这样的怎么样
using (var entity = new MyModel(ConnectionString))
{
var query = (from myTable in entity.theTable
where myTable.FacilityID == facilityID &&
myTable.FilePath != null &&
myTable.TimeStationOffHook < oldDate
orderby myTable.FilePath
select new
{
myTable,FileName,
myTable.FilePath
}).Skip(1000).Take(1000).ToList();
//do what you want with the query result here
}
使用(var实体=新的MyModel(ConnectionString))
{
变量查询=(来自entity.theTable中的myTable
其中myTable.FacilityID==FacilityID&&
myTable.FilePath!=null&&
myTable.TimeStationOffHook
只是一个问题:在订购/跳过/服用之前或之后选择子部分是否更快?或者它不会改变EF上下文中的任何内容吗?因为.ToList()
之前的所有内容都被转换为数据库查询。您不必担心它。运行时将在执行它之前生成SQL(调用ToList
)。最简单的方法是通过DBContext
记录SQL并比较不同的排列。
using (var entity = new MyModel(ConnectionString))
{
var query = (from myTable in entity.theTable
where myTable.FacilityID == facilityID &&
myTable.FilePath != null &&
myTable.TimeStationOffHook < oldDate
orderby myTable.FilePath
select new
{
myTable,FileName,
myTable.FilePath
}).Skip(1000).Take(1000).ToList();
//do what you want with the query result here
}