How can I ignore list members that are null?

0

I am using Automapper to map models in my web app.

I use this Automapper method:

protected virtual IEnumerable<TDto> Map(IEnumerable<TModel> models)
{
    return Mapper.Map<IEnumerable<TDto>>(models, MappingOptions);
}

And I use it in my own method like this:

protected override IList<EngineAssembly> GetChildren(Engine parent)
{
    return parent.EngineParts;
}
    
var parent = Session.Get<TParent>(parentId);
if (parent == null) return NotFound();
var children = GetChildren(parent);
return Ok(Map(children));

The problem is, sometimes the IList of children may contain a null entity. Which causes this error:

AutoMapper.AutoMapperMappingException
HResult=0x80131500
Message=Error mapping types.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>

Inner Exception 1:
ArgumentNullException: Value cannot be null.

But I can't figure out how to weed out any null entities that may be in the list of children.

I return a NotFound message if a parent is null, but is there a way to just ignore null children?

Thanks!

c#
list
automapper
asked on Stack Overflow Apr 29, 2021 by SkyeBoniwell

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0