Linq中这个SQL语句的等价物是什么?
我需要将此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 = '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 };
我现在有一些问题需要解决:
- 由于我加入表格位置的表格位置两次,为了获取源位置和目标位置的名称,在LinQ中执行此操作会导致编译器错误,即dl.Name,dl.Country,dl,Airport是匿名的类型和它们将与其他sl.Name,sl.Country,sl.Airport同名。
- 我不能像在Sql中那样使用“As”表达式,或者在Linq中是否有任何等价的表达式?
- 当我在linq查询中时,我无法将Tarif乘以乘客数量,而它不允许我这样做。
您可以将带有new
对象初始化程序的别名与下面的代码一起使用,这也将支持乘以tarif:
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乘以时无法从表达式中命名属性)。
通过显式命名具有冲突的属性,编译器不再需要推断生成冲突的命名。
更多: http : //geekswithblogs.net/BlackRabbitCoder/archive/2012/06/21/c.net-little-wonders-the-joy-of-anonymous-types.aspx
上面的链接有一些关于如何将对象初始化程序与匿名类型一起使用的其他示例。
这个概念称为Projection ,您必须根据您的要求选择新的匿名类型或别名。
样品:
var result = data.Select( x => new { FieldName = x.Property } );
- 将web.config部分读取到List
- 如何结合异步调用编程我的进度条?
- 如何在不访问服务的情况下将WCF WSDL和XSD共享给客户端?
- 正确使用HttpContext.Current.User与异步等待的方法
- 无法从其他类中更改textBox.text – C# – VS 2010
- .NET第三方库中是否存在任何并发队列类型?
- 如何在.net 4.0中使用asyn / await? AsyncTargetingPack和Microsoft.Bcl.Async之间的区别?
- 如何在MVC Web API post方法中将ModelState错误返回给Kendo网格?
- 通过代码打开机器/基础Web.Config(64位)