In the application I support, there are times that associations can be null as the client has not submitted the data yet. I don't know of any other way to handle this other than doing a null check. The database is set in stone (other applications consume it also) It turns my code into an mess. I was wondering if there is a better way to go about doing this (this code is going into an anonymous type, but using a class makes no difference. I can't add a predicate checking for null, because if the bill exists that information needs to be returned regardless of if claim patient or claim do not exist yet. Here is a simplified version:
var baseQuery = Context.Bills.AsNoTracking()
.Select
(
bill => new
{
bill.BillId,
bill.BillStatus,
patientId = bill.ClaimPatient != null ? bill.ClaimPatientId : null,
claimPatientId = bill.ClaimPatient != null && bill.ClaimPatient.Claim != null ? bill.ClaimPatientId : null,
bill.UserNumber,
}
);
And this null checking can go on and on. I know there is probably a better way, and when I see it I will face plant because it will probably be something so simple and obvious that I missed.
I've found extensions methods like the following are sometimes useful for dealing with this.
Some example usage follows.