Monday, 15 July 2013

c# - Avoiding null exception in EF that is thrown by your query -



c# - Avoiding null exception in EF that is thrown by your query -

i have query :

result = firstidearepository.findby( => i.firstideastate == firstideastate && i.date >= start && i.date <= end) .asenumerable() .select(j => new rptlistofcompanybasedonfirstideastate() { name = companyrepository.findby(i => i.userid == j.userid) .firstordefault() dateofmeeting = calenderrepository.converttopersiantoshow( meetingreposiotry.findby(s => s.firstideaid == j.id) .firstordefault() .date), dateofexit = calenderrepository.converttopersiantoshow(j.dateofexit.value), reasonofexit = j.reasonofexit, }).tolist(); homecoming result;

as can see utilize firstordefault() , j.dateofexit.value , date doesn't have values or sometime other variables null because utilize firstordefaut()

companyrepository.findby(i => i.userid == j.userid).firstordefault().

so query throws null exception , result can't created ,how can handle exception , illustration if .net detects null value ignores default or uses default values ?

best regards.

i create next changes:

result = firstidearepository.findby( => i.firstideastate == firstideastate && i.date >= start && i.date <= end) .asenumerable() .select(j => new rptlistofcompanybasedonfirstideastate() { name = companyrepository.findby(i => i.userid == j.userid) .firstordefault() dateofmeeting = callenderrepository.converttopersiantoshow( meetingreposiotry.findby(s => s.firstideaid == j.id) // project new sequence first, before calling `firstordefault`: .select(s => s.date) .firstordefault(), dateofexit = j.dateofexit.hasvalue ? callenderrepository.converttopersiantoshow(j.dateofexit.value) : null, reasonofexit = j.reasonofexit, }).tolist();

when utilize firstordefault, there's possibility you'll null (in case of reference types), , need plan in code.

for example, when assigning dateofmeeting, project results (using .select) before using .firstordefault, you're not ever accessing date property on null value.

as dateofexit, i've used conditional operator determine whether phone call calendarrepository's method @ all. assumes dateofexit nullable.

unrelated: "calendar" spelled 1 "l" , not two.

c# sql entity-framework nullreferenceexception

No comments:

Post a Comment