When using lambda expressions in EF, if the data is null, an error will be reported when reading the field. (Solution)

foreword

When using net5.0 and using ef to query data, there will be a case of querying a certain field value, but if the current value is empty, the lambda expression will report an error. The following explains how to solve the error


Solve the error that the obtained value in lambad is empty

Example:
string name = _dbContext.StationInfo.FirstOrDefault(q => q.Id == Id).name;
Like the lambda expression above, if there is no such data, an error will be reported directly

Solution :
string name = _dbContext.StationInfo.FirstOrDefault(q => q.Id == Id)?.name??" ";
The function of ?.name is that if the object is NULL, it will return NULL directly without performing subsequent calculations to obtain members. If this is not added, an error will be reported directly. The function of
the following is to return " " if the returned data is NULL. If yes , if the query data is NULL, it will be 0.??" "
?? 0

Guess you like

Origin blog.csdn.net/qq_37213281/article/details/128641772