2014-04-15 110 views
2

这里简单的linq转换为返回anonymous type的实体查询。问题是int?值之一使用像参数来获得另一个值是int在linq查询中将可空int转换为int返回匿名类型

我知道的所有方法都不起作用。请告知如何解决这个问题。

public IQueryable<toursistdata> GetxTouristByCategory(string category) 
     { 
      var now = System.DateTime.MinValue; 
      int i; 
      switch (category) 
      { 
       case "arrival": 
        now = System.DateTime.Now.AddDays(-3); 
        var arrival = from a in db.xTourist 
            where a.ArrDate >= now && a.Room == null 
            select new toursistdata 
            { 
             kodt = a.Kod, 
             name = a.Name, 
             paxad = a.Paxad, 
             paxch = a.Paxch, 
             **//Here is h.Kod is int but KodH is int?** 
             hotel = (from h in db.Address where h.Kod = (int)a.KodH.HasValue select h.NameC).FirstOrDefault(), 
             room = a.Room, 
             arrdate = a.ArrDate, 
             arrtime = a.ArrTime, 
             arrflight = a.ArrFl, 
             depdate = a.DepDate, 
             deptime = a.Deptime, 
             depflight = a.DepFlight, 
             transfer = a.Transfer 
            }; 
            return arrival; 
       case "inhouse": 
        now = System.DateTime.Today; 
        //return db.xTourist.AsQueryable().Where(p => p.Датапр >= now && p.Номер != null).OrderByDescending(p => p.Датапр); 
       default: 
        //return db.xTourist.AsQueryable(); 
      } 
     } 
+2

在哪一行是问题? –

+1

切勿在代码中使用非英文字符。 – AgentFire

+1

'db.Адреса'等人是他们自己的错误。 – AgentFire

回答

5

首先在等号运算符中缺少一个'='。那么,如果你想比较一个int与一个int?你可以使用Null Coalescing操作符?以提供空的情况下的默认值,然后将其转换为int

h.Kod == (a.KodH ?? 0) 
+1

没有必要显式强制转换为'int' –

+0

@LuisFilipe正确,我编辑了帖子。 – Hannes

+0

仍然是同样的错误 - 无法将int转换为布尔值。 –

2

故障线路应阅读

  • 如果你确定可空INT有一个值

from h in db.Адреса where h.Kod = a.KodH.Value select h.NameC).FirstOrDefault()

  • 或者如果可为空的可以是空值,则使用默认值

from h in db.Адреса where h.Kod = (a.KodH ?? -1) select h.NameC).FirstOrDefault()

- 或 -

from h in db.Адреса where a.KodH!= null && h.Kod= a.KodH.Value select h.NameC).FirstOrDefault()

详情与空类型的工作指MSDN Documentation