Search code examples
entity-framework-coreef-code-first

EF Core Select query with null references


I have a Select query that performs a check on a child navigation property to then check another referenced property. The first child navigation property can be null but the second property isRequired() and if the first child is not null in the database, the query runs fine but if one or more rows exist that do not have a referencing value for that property then I get -

An exception occurred while iterating over the results of a query for...

How can I make a query with an optional property run and return null for the records that have no references.

await _dbContext.NewsBoard
    .AsNoTracking()
    .Select(item => new NewsResponse
    {
        Id = item.BoardId,
        MediaType = new MediaTypeResponse 
        { 
             Id = item.Media.MediaTypeId, 
             Name = item.Media.MediaType.Name 
        },

Above is the query I am trying to run, the item.Media does not exist have a value for its foreign key (its null) and so the expected result would have been a list of NewsResponse with MediaType being null where there is a null referenced item.Media.


Solution

  • Use a null check in your query like -

    await _dbContext.NewsBoard
            .AsNoTracking()
            .Select(item => new NewsResponse
            {
                Id = item.BoardId,
                MediaType = item.Media == null ? null : new MediaTypeResponse  // null check
                {
                    Id = item.Media.MediaTypeId,
                    Name = item.Media.MediaType.Name
                }
            })
            .ToList();