无法将ApplicationUser类型转换为User

sky*_*ake 3 c# asp.net-mvc entity-framework

 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?)
Run Code Online (Sandbox Code Playgroud)

我找不到与此问题相关的任何内容.我在Controllers文件夹中创建了一个API文件夹,在API文件夹中添加了UserController,然后编写了以下内容:

(得到错误 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
        }
Run Code Online (Sandbox Code Playgroud)

这是我的用户模型:

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

}
Run Code Online (Sandbox Code Playgroud)

不知道怎么解决这个问题?

Gav*_*vin 6

您的方法返回IEnumerable<User>,但_context.Users必须让您输入ApplicationUser.您必须将这些转换为类型User,或让您的方法返回IEnumerable<ApplicationUser>.

要进行转换,我喜欢使用Transformers.我通常实现一个接口

public interface ITransformer<in TSource, out TOutput>
{
    TOutput Transform(TSource source);
}
Run Code Online (Sandbox Code Playgroud)

一个示例变压器就是

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
        };
    }
} 
Run Code Online (Sandbox Code Playgroud)