簡體   English   中英

如何查看Lambda表達式中的null列表?

[英]How to check null in Lambda Expression to list?

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();
        } 
    }
}

我正在嘗試登錄,但roleuserRole表已經沒有任何數據,因此它會引發 null 引用異常。 我能做些什么來解決這個問題? 在此處輸入圖像描述

當您在 UserRole 中為角色定義可空屬性並在 UserRole 中查找用戶但找不到角色時,會出現此問題您應該檢查角色屬性是否不是 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();

嘗試拆分 linq 查詢並讓 ToList 與 null 檢查分開調用。

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 != null ? x.Role.Name : "Not available" })
                    .ToList();
        } 
    }
}

基本上我在這里所做的,我應用了三元條件運算符,以防你的角色與 null 不同時我們將讀取數據,否則我會將名稱設置為某個默認值“不可用”,但你可以將其設置為任何你想要的到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM