Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling null nested values when using .Select() in Lambda with Entity Framework

We are having a hard time trying to figure out the best way to handle this with out declaring a loop after you get the data.

For instance take this piece of code: (Data2 is tied to Data with a foreign key)

context.Data.Select(_ => new DataModel
                    {
                        Id = _.Id,
                        Data2 = new Data2Model
                        {
                            Id = _.Data2.Id,
                            Name = _.Data2.Name,
                            Date = _.Data2.Date
                        },
                        Date = _.Date                                           
                     });

If _.Data2 is not null then this runs correctly but if _.Data2 happens to be null then this will error. The way we are getting around this now is to add Data2Id to our DataModel and then loop through all of the records to get the information if its not null.

var lst = context.Data.Select(_ => new DataModel
                             {
                                 Id = _.Id,
                                 Data2Id = _.Data2ID
                                 Date = _.Date                                           
                              }).ToList();

foreach(var item in lst)
{
     if (item.Data2Id != null) 
     {
         var dataItem = context.Data2.FirstOrDefault(_ => _.Id == item.Data2Id);
         item.Data2 = new Data2Model
         {
             Id = dataItem.Id,
             Name = dataItem.Name,
             Date = dataItem.Date
         }
      }
}

Is there a cleaner / better way to keep this in the original select loop.

Thanks

like image 284
NormTheThird Avatar asked Aug 28 '26 15:08

NormTheThird


2 Answers

Try:

Data2 = _.Data2 == null ? null : new Data2Model
{
    Id = _.Data2.Id,
    Name = _.Data2.Name,
    Date = _.Data2.Date
},
like image 84
Pablo notPicasso Avatar answered Aug 31 '26 05:08

Pablo notPicasso


context.Data.Select(_ => new DataModel
                    {
                        Id = _.Id,
                        Data2 = _.Data2 == null ? 
                        new Data2Model{Id = _.Data2ID} :
                        new Data2Model{ Id=_.Data2.Id, Name=_.Data2.Name, Data=_.Data2.Date},    
                        Date = _.Date                                           
                     });

I'm making the assumption that if it is null you still have the _.Data2ID at hand?

Using the ternary operator

If Data2 is null then return a new Data2Model with just the other _.Data2ID value

If it is not null then go ahead and create a new Data2Model with all the details.

like image 45
AnonyMouse Avatar answered Aug 31 '26 04:08

AnonyMouse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!