繁体   English   中英

无法投射 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[Microsoft.AspNetCore.Identity.IdentityUser`1[System.Int32]]'

[英]Cannot cast 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[Microsoft.AspNetCore.Identity.IdentityUser`1[System.Int32]]'

问题:

System.InvalidCastException:“无法将类型为‘Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1[Microsoft.AspNetCore.Identity.IdentityUser 1[System.Int32]]”的 object 转换为键入“System.Linq.IQueryable”1[DAL.User ]'.'

相关代码:

...
public class SocialNetworkDbContext : IdentityDbContext<IdentityUser<int>, IdentityRole<int>, int> 
...
public IQueryable<User> FindAll()
        {
            var allUsers = (IQueryable<User>)_socialNetworkDbContext.Users;
            if (allUsers == null)
            {
                throw new NoRecordFoundException();
            }
            return allUsers;

试过:

  1. public class SocialNetworkDbContext: IdentityDbContext<User>, IdentityRole<int>, int>

//没有例外,但这段代码中断

            var result = await _userManager.CreateAsync(user, model.Password);
            await _userManager.AddToRoleAsync(user, model.Role);
  1. public IQueryable FindAll() { var allUsers = (IQueryable)_socialNetworkDbContext.Users.AsQueryable(); if (allUsers == null) { throw new NoRecordFoundException(); } 返回所有用户;

//同样的异常

3)

public IQueryable<User> FindAll()
        {
            var allUsers = (IQueryable<User>)(IEnumerable<User>)_socialNetworkDbContext.Users;
            if (allUsers == null)
            {
                throw new NoRecordFoundException();
            }
            return allUsers;

// 相同的异常(无法转换为 IEnumerable)。 投射到 ICollection(无法投射到 ICollection)

非常感谢任何建议!

您应该更改 DbContext 以使用实际的用户类型:

public class SocialNetworkDbContext : IdentityDbContext<User, IdentityRole<int>, int>
{
}

如果角色有 class,则也应将其用作通用类型参数。 这样你就不需要任何类型转换。

从您的代码看来, _socialNetworkDbContext.Users存储的是 IdentityUser,而不是用户 model,对吗? 所以,从Users表中查询数据后,可以使用如下代码对查询结果进行转换:

    public IQueryable<User> FindAll()
    { 
        var allUsers = _socialNetworkDbContext.Users.Select(c => new User()
        {
            UserName = c.UserName,
            Email = c.Email,
            //... other properties
        }).AsQueryable();
        if (allUsers == null)
        {
            throw new NoRecordFoundException();
        }
        return allUsers;
    }

更新

您可以参考以下示例代码:

添加一个ApplicationUser class 自定义Identity User model:

public class ApplicationUser : IdentityUser<int>
{ 
    public string CustomTag { get; set; }
}

使用 ApplicationUser 类型作为上下文的通用参数:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
{
    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

更新 Pages/Shared/_LoginPartial.cshtml 并将 IdentityUser 替换为 ApplicationUser:

@using Microsoft.AspNetCore.Identity
@using WebApp1.Areas.Identity.Data
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

更新Startup.ConfigureServices并将IdentityUser替换为ApplicationUser

public void ConfigureServices(IServiceCollection services)
{ 
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDatabaseDeveloperPageExceptionFilter();

    services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

    services.AddControllersWithViews();
}

然后,启用迁移并生成数据库。

创建新用户后,AspNetUser 表数据如下:

在此处输入图像描述

创建一个 UserViewModel 并添加所需的属性:

public class UserViewModel
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Tag { get; set; }
}

然后,在Controller中,使用如下代码查询user表:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly ApplicationDbContext _context;
    public HomeController(ILogger<HomeController> logger, ApplicationDbContext context)
    {
        _logger = logger;
        _context = context;
    }

    public IActionResult Index()
    {
        var result = FindAll();
        return View();
    }
    public IQueryable<UserViewModel> FindAll()
    {
        var allUsers = _context.Users.Select(c => new UserViewModel()
        {
            UserId = c.Id,
            UserName = c.UserName,
            Tag = c.CustomTag
        });
        //if (allUsers == null)
        //{
        //    throw new NoRecordFoundException();
        //}
        return allUsers;
    }

结果如下:

在此处输入图像描述

先试试(); 或 FirstOrDefault();

改变你的代码:

    public async Task<List<User>> GetAllUsers()
        {
            var allUsers =  await _socialNetworkDbContext.Users.ToListAsync();
            if (allUsers == null)
            {
                throw new NoRecordFoundException();
            }
            return allUsers;
         }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM