skylake skylake - 1 year ago 58
C# Question

Cannot implicity convert type ApplicationUser to User

Cannot implicitly convert type
'System.Collections.Generic.List<xxxx.Models.ApplicationUser>' to
'System.Collections.Generic.IEnumerable<xxxx.User>'. An explicit
conversion exists (are you missing a cast?)

I can't find anything related to this issue. I created an API-folder inside Controllers folder, added UserController in API folder and then wrote the following:

(get the error at
return _context.Users.ToList();

namespace xxxx.Controllers.API {
public class UserController : ApiController

private ApplicationDbContext _context;

public UserController() {
_context = new ApplicationDbContext();

//GET /api/users
public IEnumerable<User> GetUsers()

return _context.Users.ToList(); //<-- where I get the error message

This is my model for user:

public partial class User
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
this.Reviews = new HashSet<Review>();

public System.Guid Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Review> Reviews { get; set; }


Any idea how to solve this?

Answer Source

Your method returns IEnumerable<User>, but _context.Users must get you type ApplicationUser. You will have to convert these to type User, or have your method return IEnumerable<ApplicationUser>.

To do the conversion, I like to use Transformers. I usually implement an interface

public interface ITransformer<in TSource, out TOutput>
    TOutput Transform(TSource source);

An example transformer would be

public class AppUserToUserTransformer : ITransformer<ApplicationUser, User>
    public User Transform(ApplicationUser source)
        return new User
            Username = source.Username;
            Email = source.Email;
            //continue with the rest of the available properties