Search code examples
c#linqnullable

Convert nullable int to int in linq query return anonymous type


here simple linq to entities query that return anonymous type. The problem is that one of the int? values used like parameter to get another value that is int.

All ways that I know is not working. Please advise how to solve this problem.

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();
            }
        }

Solution

  • First there is one '=' missing in your equals operator. Then, if You want to compare an int with an int? you can use the Null Coalescing operator ?? to provide a default value for the null-case , then cast it to an int:

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