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
Try:
Data2 = _.Data2 == null ? null : new Data2Model
{
Id = _.Data2.Id,
Name = _.Data2.Name,
Date = _.Data2.Date
},
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With