用linq语法编写sql查询

时间:2014-05-30 14:23:07

标签: c# sql sql-server linq

我试图用linq语法编写以下查询,但我可以做到。我在标记的行Error The best overloaded method match for 'System.Collections.Generic.List<AnonymousType#1>.Contains(AnonymousType#1)' has some invalid arguments 上收到错误。我该怎么写得好呢?

SQL:

     select * from [dbo].[TableOrder]
     where TableID not in (
     select tbl.TableID from [dbo].[TableOrder] tbl
     left join [dbo].[Restorant] r on tbl.RestorantID = r.RestorantID 
     left join [dbo].[Reservation] res on res.TableID = tbl.TableID
     where ReservationDate = '15.06.2014' and ResStartTime = '2100' and ResEndTime='2299')

linq:

            var query = (from t in db.TableOrderTbls.AsQueryable()
                     join r in db.RestorantTbls on t.RestorantID equals r.RestorantID
                     join res in db.ReservationTbls on t.TableID equals res.TableID
                     where (resv.RseservationDate == res.ReservationDate && resv.RestorantName == r.RestorantName) && ((Convert.ToInt32(resv.ResStartTime) < Convert.ToInt32(res.ResStartTime) &&Convert.ToInt32(resv.ResEndTime) < Convert.ToInt32(res.ResStartTime))||((Convert.ToInt32(resv.ResStartTime) > Convert.ToInt32(res.ResEndTime) && Convert.ToInt32(resv.ResEndTime) > Convert.ToInt32(res.ResEndTime))))
                     select new {r.RestorantName, r.RestorantID, t.TableID, t.TableType}).ToList();

        var q = from t in db.TableOrderTbls.AsQueryable()
                where query.Contains(t.TableID) // ERROR LINE
                select t;

1 个答案:

答案 0 :(得分:1)

您的查询对象是以下列表:

select new {r.RestorantName, r.RestorantID, t.TableID, t.TableType}

但是你想看看它是否包含:

TableOrderTbls.TableId

匿名{r.RestorantName, r.RestorantID, t.TableID, t.TableType}TableOrderTbls.TableId的类型不同。

您需要更具体地将匿名类型映射到TableOrderTbls.TableId

疯狂猜测,试试这个:

where query.Any(x => x.TableID == t.TableID)