[英]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:试过:
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);
//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.