Home > Software design >  How to check null in Lambda Expression to list?
How to check null in Lambda Expression to list?

Time:04-03

namespace DataAccess.Concrete.EntityFramework
{
    public class UserDal : EfEntityRepositoryBase<User, LogisticContext>, IUserDal
    {
        public List<Role> GetRoles(User user)
        {
            using var context = new LogisticContext();

            return context.UserRoles
                    .Include(x => x.Role)
                    .Where(x => x.UserId == user.Id)
                    .Select(x => new Role { Id = x.RoleId, Name = x.Role.Name })
                    .ToList();
        } 
    }
}

I'm trying to login but already, role and userRole tables dont' have any data, so it throws a null reference exception. What can i do to solve this problem?. enter image description here

CodePudding user response:

The problem was on .DefaultIfEmpty(null)

Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

Returns IEnumerable<TSource>

An IEnumerable that contains defaultValue if source is empty; otherwise, source.

As the query is materialized and there is no record queried from the database, with .DefaultIfEmpty(null) it returns you with the result: new Enumerable<UserRole> { null }.

Hence you will get NullReferenceException while accessing the RoleId and Role from x which is null.


Solution

You have to remove .DefaultIfEmpty(null) part.

return context.UserRoles
    .Include(x => x.Role)
    .Where(x => x.UserId == user.Id)
    .Select(x => new Role { Id = x.RoleId, Name = x.Role.Name })
    .ToList();

Scenario:

As both UserRole and Role tables return no record from the query, you will get the result of new List<UserRoles> {} which is an empty list/array.

CodePudding user response:

Try to split the linq query and let the ToList call apart with null checking.

CodePudding user response:

This problem occurs when you Define Nullable Property For Role In UserRole And User Find In UserRole But Role Not Found You Should Check Role Property Is Not Null

return context.UserRoles
  .Include(x => x.Role)
  .Where(x => x.UserId == user.Id && x.Role != null)
  .Select(x => new Role { Id = x.RoleId, Name = x.Role.Name })
  .ToList();
  • Related