The first ternary statement in the following code is returning “null”. myID is coming back as null. However, if the ternary statement worked properly, and a.someID is null, then myID should come back as -1. myID is a nullable int field. Do you know why I’m not getting back a -1? Thanks.
public List<myView> GetRecords()
{
myEntities entities = new myEntities();
var myValue = (from a in entities.myEntitiesA
join b in entities.myEntitiesB on a.myID equals b.myID into myEntitesC
from c in myEntitesC.DefaultIfEmpty()
select new myView
{
myID = a.someID == null ? -1 : a.someID,
myName = a.myName,
myAlternateID = c.myID == null ? -1 : c.myID,
myAlternateName = c.myName == null ? "" : c.myName,
}).Distinct().OrderBy(b => b.myName).ToList();
return (myValue);
}
EDIT – I’ve gotten rid of the DefaultIfEmpty() for the sake of testing, but my results are the same.
While all of the other answers seem valid, none of them work for me. Since I was calling this GetRecords() method from a JsonResult controller method, I ended up performing additional logic on my JsonResult, checking for NULLs a second time. This, of course, is a redundant check so it’s not ideal, but it DOES work.