How to handle no results in LINQ? -


in example code

public company getcompanybyid(decimal company_id) {     iqueryable<company> cmps = c in db.companies                                c.active == true &&                                       c.company_id == company_id                                select c;     return cmps.first(); } 

how should handle if there no data in cmps?

cmps will never null, how can check non existing data in linq query?

so can avoid this

'cmps.tolist()' threw exception of type ... {system.nullreferenceexception} 

when transforming into, example, list

getcompanybyid(1).tolist(); 

do always need wrap in try catch block?

you can use queryable.any() (or enumerable.any()) see if there member in cmps. let explicit checking, , handle wish.

if goal return null if there no matches, use firstordefault instead of first in return statement:

return cmps.firstordefault(); 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -