0

I am getting NullReferenceException when doing left outer join.

Similar query works in LINQ Pad but not in Visual Studio 2015. System.NullReferenceException was unhandled by user code HResult=-2147467261 Message=Object reference not set to an instance of an object.

Thanks in advance.

.Net Core LINQ Code that does not work:

    public IEnumerable<R> GetAll()
    {
        var results =
            from a in uow.R.GetAll()
            join b in uow.SSR.GetAll() on a.ID equals b.RID into g9
            from c in g9.DefaultIfEmpty()
            join d in uow.SS.GetAll() on c.SSID equals d.ID into g10
            from e in g10.DefaultIfEmpty()
            select new
            {
                a.Id,
                SSID = c == null ? null : (int?)c.SSID,
                e.Name
            };
        List<R> rList = new List<R>();
        foreach (var a in results)
        {
            resourceList.Add(new R { ID = a.Id, SSID = a.SSID });
        }
        return rList.ToArray<R>();
    }
`
    var Result =    
    from a in Tbl_R             
    join b in Tbl_SS on a.ID equals b.RID into g9
    from c in g9.DefaultIfEmpty()           
    join d in Lu_SS on c.SSID equals d.SSID into g10
    from e in g10.DefaultIfEmpty()
    select new
    {
        a.ID,
        SSID = c == null ? null : (int?)c.SSID,
        e.Name
    };
    Result.Dump();


SELECT t2.ID,
ISNULL(t17.SSID,'') as SSID
ISNULL(t17.Name,'') as Name
FROM R t2  
LEFT JOIN SSR t16 ON t16.RID=t2.ID
LEFT JOIN SS t17 ON t16.SSID=t17.SSID
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Fabiano May 16 '17 at 06:36
  • Please put more effort into formatting your code. I very much doubt that what it looks like in Visual Studio - the indentation is *really* important for readability. – Jon Skeet May 16 '17 at 06:41
  • Note that the `from c in g9.DefaultIfEmpty()` means that `c` can be null... so the fact that you're using `c.SSID` immediately afterwards is problematic. – Jon Skeet May 16 '17 at 06:42
  • Jon Skeet, my assumption is that SSID = c == null ? null : (int?)c.SSID is supposed to take care of this problem. Can you suggest how to fix this issue? – AnthonyGonsalves May 16 '17 at 17:35
  • I believe he is referring to `join d in uow.SS.GetAll() on c.SSID equals d.ID into g10` – NetMage May 16 '17 at 17:51
  • Can you please provide updated code for how query will look like with your suggested changes? – AnthonyGonsalves May 16 '17 at 18:08
  • I have also posted SQL. Both SQL and LINQPAD SQL works great.I am just trying to recreate SQL into LINQ but it is taking days and this is making me less confident in using LINQ (vs. sprocs). I will appreciate quick response. – AnthonyGonsalves May 16 '17 at 20:06
  • Guys...looking for your ideas to fix this issue. – AnthonyGonsalves May 18 '17 at 00:35

0 Answers0