【问题标题】:Generic function given showing exception给出显示异常的通用函数
【发布时间】:2025-12-07 08:10:02
【问题描述】:

我在存储库中编写了以下存储库函数,它没有显示数据。

 public async Task<IEnumerable<User>> GetAllUser()
    {
        return await FindByCondition(ur => ur.IsDeleted != true).Include(x => x.UserRole.RoleType).ToListAsync();
    }

这个的通用函数是:

public IQueryable<TEntity> FindByCondition(Expression<Func<TEntity, bool>> expression)
        {
            return _mBHDbContext.Set<TEntity>().Where(expression).AsNoTracking();
        }

上面的代码写的时候出现异常:

当“包含”与查询一起使用时会出现此错误。意味着当我们需要来自两个表的数据时,问题就会出现。

而我的实体模型结构是这样的:

 public partial class User
    {
        public User()
        {
            PatientAnswers = new HashSet<PatientAnswer>();
        }

        public long UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool? IsDeleted { get; set; }
        public int? UserRoleId { get; set; }
        public DateTime? DataOfBirth { get; set; }

        public virtual RoleMaster UserRole { get; set; }
        public virtual ICollection<PatientAnswer> PatientAnswers { get; set; }
    }

其他表结构如下:

public partial class RoleMaster
    {
        public RoleMaster()
        {
            Users = new HashSet<User>();
        }

        public int Id { get; set; }
        public string RoleType { get; set; }

        public virtual ICollection<User> Users { get; set; }
    }

【问题讨论】:

    标签: c# generics .net-core


    【解决方案1】:

    尝试使用以下内容。这会将信息带入链接的UserRole 实体中,并避免访问RoleType 时的往返

    public async Task<IEnumerable<User>> GetAllUser()
        {
            return await FindByCondition(ur => ur.IsDeleted != true).Include(x => x.UserRole).ToListAsync();
        }
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用ThenInclude

      public async Task<IEnumerable<User>> GetAllUser()
      {
          return await FindByCondition(ur => ur.IsDeleted != true)
            .OrderBy(ro => ro.UserId)
            .Include(x => x.UserRoleNavigation)
            .ThenInclude(ur => ur.RoleType)
            .ToListAsync();
      }
      

      【讨论】:

        【解决方案3】:

        它抱怨Include(x =&gt; x.UserRole.RoleType) 表达式。

        包含期望包含的 lambda 指向导航属性,所以我看到它是 x.UserRole

        此外,Inlucde value 属性没有意义,例如字符串。如果你想访问它(从db中获取它),包含它的导航属性就足够了,所以你只需要Include(x =&gt; x.UserRole)

        【讨论】: