我有一个火车数据库,其中包含所有必填字段,例如火车,路线,车站,乘客,预订等。我想使用LINQ在一对车站之间获得火车(我知道SQL查询,但是我无法将其转换为LINQ)。请任何人帮助我。
还有一件事情,我想要LINQ查询的 Extension方法方法(不是像from,in,select 这样的关键字),例如
var trains = _context.Trains.FirstOrDefault(a => a.Id == text);
SQL查询
SELECT Route.TrainId, Train.TrainName
FROM Route
INNER JOIN Train ON Route.TrainId=Train.TrainId
WHERE
(Route.StationId IN
(SELECT Source.StationId
FROM Route AS Source
INNER JOIN Route AS Destination ON Source.TrainId=Destination.TrainId
WHERE
(Source.StopNumber - Destination.StopNumber < 0)
AND
(Source.StationId = @Source)
AND
(Destination.StationId = @Destination)
)
)
如果您想要更多详细信息,例如表结构,请评论我。我从在线幻灯片中获得了表结构和查询。
答案 0 :(得分:0)
我使用类对数据库进行建模。试试这样的东西
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Train> trains = new List<Train>();
string source = "abc";
string destination = "xyz";
var results = trains.Where(x => x.Routes.Any(y => y.StationId == source) && x.Routes.Any(y => y.StationId == destination))
.Select(x => new {
source = x.Routes.Where(y => y.StationId == source).FirstOrDefault(),
destination = x.Routes.Where(y => y.StationId == destination).FirstOrDefault()
})
.Where(x => x.destination.StopNumber > x.source.StopNumber)
.ToList();
}
}
public class Train
{
public string TrainName { get; set; }
public List<Route> Routes { get; set; }
}
public class Route
{
public string TrainId { get; set; }
public string StationId { get; set; }
public int StopNumber { get; set; }
}
}