簡體   English   中英

在linq查詢中將nullable int轉換為int返回匿名類型

[英]Convert nullable int to int in linq query return anonymous type

這里簡單的linq to實體查詢返回anonymous type 問題是其中一個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();
            }
        }

首先,你的equals運算符中缺少一個'='。 那么,如果你想比較int和int? 你可以使用Null Coalescing運算符?? 為null-case提供默認值,然后將其強制轉換為int

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

錯誤的行應該讀取

  • 如果你確定nullable int有一個值

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

  • 或者如果nullable可以為null,則使用默認值

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文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM