Home > Enterprise >  Unable to cast object of type 'System.Collections.Generic.List[Interfaces.IUser] to type '
Unable to cast object of type 'System.Collections.Generic.List[Interfaces.IUser] to type '

Time:10-10

I don't know what is a problem I'm using the Repository pattern in API request here is the code

In Repository

public IQueryable<IUser> Get()
{
        return _mapper.Map<IQueryable<IUser>>(_context.Users.AsQueryable());
}

In API

// GET: api/UserEntities
public IQueryable<UserEntity> GetUsers()
{
        return _mapper.Map<IQueryable<UserEntity>>(_repository.Get());
}

CodePudding user response:

Let's start from the basics. This piece of code:

public IQueryable<IUser> Get()
{
    return _mapper.Map<IQueryable<IUser>>(_context.Users.AsQueryable());
}

is completely wrong in multiple ways:

  • You should not return IQueryable<T>. That leaks the Entity Framework dependency.
  • You should not run a mapper against an IQueryable<T>, but rather against elements of the result.
  • Doing AsQueryable() on an IQueryable<T> is the same as doing "string".ToString() -> no effect, at all.
  • Changing AsQueryable() for AsEnumerable() would return the entire table synchronously.

Even if this is just for learning purposes, this is entirely incorrect, and you're just learning terribly wrong practices. It's best to learn how to do things correctly from the beginning.

Since you are using Entity Framework, and clearly leaking the dependency isn't an issue, let's get rid of that entire method and do it correctly:

// GET: api/UserEntities
public async Task<IEnumerable<UserEntity>> GetUsersAsync()
{
    var users = await _context.Users
        .Select(x => _mapper.Map<UserEntity>(x))
        .AsNoTracking()
        .ToArrayAsync();

    return users;
}

Entity Framework implements Unit of Work and Repository patterns, so putting it behind another Repository is a waste of time that only adds complexity with no added benefit except in the rare cases where removing EF is a real option.

CodePudding user response:

Here is how I simply fixed it, In Repository

public IQueryable<IUser> Get()
{
    return _mapper.Map<List<IUser>>(_context.Users).AsQueryable();
}

In API

public IQueryable<UserEntity> GetUsers()
{
    return _mapper.Map<List<UserEntity>>(_repository.Get()).AsQueryable();
}
  • Related