C# LinqToSql中的子查询
我有几张桌子,可以概括为:C# LinqToSql中的子查询,c#,sql,sql-server,entity-framework,C#,Sql,Sql Server,Entity Framework,我有几张桌子,可以概括为: Bookings +--------+------+------------+ | BKName | BkId | BkActivity | +--------+------+------------+ Functions +-------+--------+------+-----+-------+---------+---------+ | FName | FStart | FEnd | FID | FBkId | FRmCode | FEvents | +---
Bookings
+--------+------+------------+
| BKName | BkId | BkActivity |
+--------+------+------------+
Functions
+-------+--------+------+-----+-------+---------+---------+
| FName | FStart | FEnd | FID | FBkId | FRmCode | FEvents |
+-------+--------+------+-----+-------+---------+---------+
Rooms
+--------+--------+
| RmName | RmCode |
+--------+--------+
F2
+----------+------+
| UniqueId | Item |
+----------+------+
B2
+----------+------+
| UniqueId | Item |
+----------+------+
在SQL中,我的查询是
Select b.BkName
r.RmName
f.FName
f.FStart
f.FEnd
f.FID
From Bookings as b
Inner Join Functions as f
on b.BkId = f.BkId
Left Outer Join Rooms as r
on f.FRmCode = r.RmCode
Where (b.BkActivity <> 'C') and (f.FEvents = 1)
and isnull((Select Item
from F2
where UniqueId = F.FID),0)=0
and isnull((Select Item
from B2
where UniqueId = b.BkId),0)=0
我正在尝试使用Enity框架和扩展的LINQtoSQL,但要想得到同样的信息,我花了很长时间。我相信我的问题是两个子查询把事情搞砸了,还有左外连接。我尝试过的所有变体最终都没有返回任何结果。您可以尝试以下代码:
var bookings = GetBookings();
var functions = GetFunctions();
var rooms = GetRooms();
var f2 = GetF2();
var b2 = GetB2();
var result = from booking in bookings
join function in functions on booking.Id equals function.FBkId
join room in rooms on function.FRmCode equals room.Code into bfr
from entry in bfr.DefaultIfEmpty()
where booking.Activity != "C" && function.FEvents == 1
&& (from i in f2 where i.UniqueId == function.FId select i.Item).FirstOrDefault() == 0
&& (from i in b2 where i.UniqueId == booking.Id select i.Item).FirstOrDefault() == 0
select new
{
BookingName = booking.Name,
RoomName = entry.Name,
FunctionName = function.Name,
Start = function.Start,
End = function.End,
FId = function.FId
};
了解列的类型会很有帮助。我还尝试优化where子句中的查询,但这需要更多关于数据库的知识。请记住,此代码的性能可能不如SQL存储过程。如果性能对您很重要,我建议您记录SQL输出并测量执行select所需的时间。值得发布您当前尝试使用Entity Framework的情况,即使它没有按预期工作。这对我来说并不完全有效,但它让我走上了正确的方向。出于无法解释的原因,我不得不在main之外进行两个独立的子查询,将f2连接到函数,将b2连接到bookings,然后使用where语句中的子查询。我相信这是因为我在他们身上使用了DefaultIfEmpty。我仍然会接受这一点,因为它使我在正确的轨道上几乎没有修改。