score:0

You can get around this by always returning the anonymous where the anonymous object may have null properties.

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = new { Name = p.SecondaryId.HasValue ? p.Secondary.Name : null }
    });
}

And if you really want to make Secondary null if p.SecondaryId is null you can add the following.

//ToList allows you to work with LINQ to Objects rather than Linq to Entities.  
//However, you'll generally want to call ToList() last for performance reasons.
var valsCleaned = vals.ToList()
                      .Select(v => { 
                                       if(v.Secondary.Name == null)
                                       {
                                           v.Secondary == null;
                                       }
                                       return v;
                                   });

score:0

I don't have a "solution" per se. To workaround this issue, I simply projected the entire secondary entity. I'm not happy with this solution.

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = p.Secondary
    });
}

Obviously, projecting an entire entity is akin to "SELECT *" - which is a bad practice. And it may not work for you, depending on your actual query.


Related Articles