简体   繁体   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]]'

PROBLEM:问题:

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

RELEVANT CODE:相关代码:

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

TRIED:试过:

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

//no exception but this code breaks //没有例外,但这段代码中断

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

//the same exception //同样的异常

3) 3)

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

// the same exception (unable to cast to IEnumerable). // 相同的异常(无法转换为 IEnumerable)。 Cast to ICollection (unable to cast to ICollection)投射到 ICollection(无法投射到 ICollection)

Would be very thankful for any advice!!!非常感谢任何建议!

You should change your DbContext to use the actual user type:您应该更改 DbContext 以使用实际的用户类型:

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

If you have a class for the roles, you should use that as the generic type argument as well.如果角色有 class,则也应将其用作通用类型参数。 This way you won't need any type casts.这样你就不需要任何类型转换。

From your code, it seems that the _socialNetworkDbContext.Users was stored the IdentityUser, instead of User model, right?从您的代码看来, _socialNetworkDbContext.Users存储的是 IdentityUser,而不是用户 model,对吗? So, after query data from the Users table, you could use the following code to convert the query result:所以,从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;
    }

Update更新

You can refer the following sample code:您可以参考以下示例代码:

Add an ApplicationUser class to customize the Identity User model:添加一个ApplicationUser class 自定义Identity User model:

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

Use the ApplicationUser type as a generic argument for the context:使用 ApplicationUser 类型作为上下文的通用参数:

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

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

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

Update the Startup.ConfigureServices and replace IdentityUser with ApplicationUser :更新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();
}

Then, enable migration and generate the database.然后,启用迁移并生成数据库。

After creating new user, the AspNetUser table data as below:创建新用户后,AspNetUser 表数据如下:

在此处输入图像描述

Create a UserViewModel and add the required properties:创建一个 UserViewModel 并添加所需的属性:

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

Then, in the Controller, use the following code to query the user table:然后,在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;
    }

The result as below:结果如下:

在此处输入图像描述

try First();先试试(); or FirstOrDefault();或 FirstOrDefault();

change your code:改变你的代码:

    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.

相关问题 没有注册“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered Microsoft.AspNetCore.Identity.EntityFrameworkCore.dll 中发生“System.InvalidOperationException” - 'System.InvalidOperationException' occurred in Microsoft.AspNetCore.Identity.EntityFrameworkCore.dll SetField 无法将 DBNull.Value 转换为 System.Int32 - SetField cannot cast DBNull.Value to System.Int32 从“System.Int32”到“System.Nullable”1[[System.Int32, mscorlib]] 的无效转换 - Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib]] 使用反射从“System.Int32”到枚举的无效转换 - Invalid cast from 'System.Int32' to Enum using reflections 没有类型“Microsoft.AspNetCore.Identity.UserManager”的服务:在尝试扩展 IdentityUser 时? - No service for type 'Microsoft.AspNetCore.Identity.UserManager' : while trying to extend IdentityUser? 错误“无法将'System.Int32'类型的对象强制转换为'System.Collections.Generic.List`1 [System.Int32]'' - error “Unable to cast object of type 'System.Int32' to type 'System.Collections.Generic.List`1[System.Int32]'” 无法在System.String和System.Int32上执行&#39;=&#39;操作? - Cannot perform '=' operation on System.String and System.Int32? 没有注册 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext' 类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext' has been registered 将 Microsoft.AspNetCore.Identity 默认表的 id 设置为 int - setting Microsoft.AspNetCore.Identity default tables's ids to int
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM