无法将ApplicationUser类型转换为User

时间:2016-10-02 15:47:59

标签: 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?)

我无法找到与此问题相关的任何内容。我在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
        }

这是我的用户模型:

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

}

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

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

要进行转换,我想使用Transformers。我通常实现一个接口

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

示例转换器将是

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