这个 SQL 语句在 Linq 中的等价物是什么?

2024-05-24

我需要将此 SQL 语句移植到 LINQ:

SELECT f.ID as IdFlight, 
       Tarif * 1 as Tarif, 
       f.Time, f.TimeOfArrival, 
       sl.Name as FromLoc, 
       sl.Country as FromCountry, 
       sl.Airport as FromAirport,
       dl.Name as ToLoc, 
       dl.Country as ToCountry, 
       dl.Airport as ToAirport 
FROM Flights as f 
    INNER JOIN Locations as sl ON sl.ID = f.ID_Source  
    INNER JOIN Locations as dl ON dl.ID = f.ID_Destination 
    INNER JOIN FlightsTarifs as ftf ON f.Id = ftf.IDFlight 
WHERE f.ID_Destination =30005 AND f.Time <= DATEADD(day,4,'2018/05/24 00:00') 
AND f.Time >= '2018/05/24 00:00' ORDER By f.Time, Tarif

我在 Linq 中的尝试:

IQueryable qinfo = from f in context.Flights
                   join sl in context.Locations on f.Id_Source equals sl.ID
                   join dl in context.Locations on f.Id_Destination equals dl.ID
                   join ftf in context.FlightsTarifs on f.ID equals ftf.IDFlight
                   where (f.Id_Source == aFormUser.FlightSrcID)
                   where (f.Id_Destination == aFormUser.FlightDestID)
                   where (f.Time.Date >= aFormUser.DepartureDate.Date)
                   where (f.Time.Date <= aFormUser.DepartureDate.Date.AddDays(4))
                   orderby f.Time, ftf.Tarif
                   select new {f.ID, ftf.Tarif, f.Time, f.TimeOfArrival,
                               sl.Name, sl.Country, sl.Airport,
                               dl.Name, dl.Country, dl.Airport  };

我现在有一些问题需要解决:

  1. 由于我将表航班与表位置连接两次,以便获取源位置和目的地位置的名称,因此在 LinQ 中执行此操作会导致编译器错误,即 dl.Name、dl.Country、dl、Airport 是匿名的类型,并且它们最终将具有与其他 sl.Name、sl.Country、sl.Airport 相同的名称。
  2. 我无法像在 Sql 中那样使用“As”表达式,或者 Linq 中是否有等效的表达式?
  3. 当我在 linq 查询中时,我无法将关税乘以乘客数量,但它不允许我这样做。

您可以将别名与new对象初始值设定项包含以下代码,该代码也支持乘以关税:

select new {
    f.ID,
    Tarif = ftf.Tarif * 1, // Alias and multiply by your number
    f.Time,
    f.TimeOfArrival,
    SourceName = sl.Name, // Alias
    SourceCountry = sl.Country, // Alias
    SourceAirport = sl.Airport, // Alias
    DestName = dl.Name, // Alias
    DestCountry = dl.Country, // Alias
    DestAirport = dl.Airport // Alias
};

只是为了提供更多详细信息,以防其他人偶然发现这一点,根本原因是代码使用了new关键字来定义带有对象初始值设定项的匿名类型,该对象初始值设定项在尝试定义匿名类时遇到多个冲突(多个属性具有相同的推断名称,然后当 tarif 相乘时无法从表达式命名属性)。

通过显式命名有冲突的属性,编译器不再需要推断产生冲突的命名。

More: http://geekswithblogs.net/BlackRabbitCoder/archive/2012/06/21/c.net-little-wonders-the-joy-of-anonymous-types.aspx http://geekswithblogs.net/BlackRabbitCoder/archive/2012/06/21/c.net-little-wonders-the-joy-of-anonymous-types.aspx

上面的链接有一些关于如何将对象初始值设定项与匿名类型一起使用的其他示例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

这个 SQL 语句在 Linq 中的等价物是什么? 的相关文章

随机推荐