Home > Mobile >  Generic function given showing exception
Generic function given showing exception

Time:12-11

I wrote following repository function in the repository and it is not showing the data.

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

Generic function for this is:

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

It shows exception when writing the above code:

Here is the exception screen sort

This error comes when "include" is using with the query. Means when we need data from two tables the problem showing.

And my entity model structure is look like:

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

and other table structure is look like:

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

CodePudding user response:

Try using the below. This brings the information inside linked UserRole entity and avoids a round trip when accessing RoleType

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

CodePudding user response:

You can use ThenInclude like this:

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

CodePudding user response:

It complains about Include(x => x.UserRole.RoleType) expression.

Include expect lambda poiting navigation property to include, so as I see it it's x.UserRole.

Moreover it does not make sense to Inlucde value property, such as string. If you want to access it (fetch it from db), it's enought to include navigation property that contains it, so after all, you need only Include(x => x.UserRole)

  • Related