[英]ApplicationUser always null ASP.NET CORE 3.0 Identity
When I try to get my users från the table AspNetUsers the users always return null even though there is a user in the table.当我尝试从表 AspNetUsers 获取我的用户时,即使表中有用户,用户也总是返回 null。
public class ApplicationUser : IdentityUser
{
public int Rating { get; set; }
public string ProfileImageUrl { get; set; }
public DateTime MemberSince { get; set; }
public bool IsActive { get; set; }
}
What I want to show is Posts with Author information我想显示的是带有作者信息的帖子
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual Foorum Forum { get; set; }
public virtual IEnumerable<PostReply> PostReplies { get; set; }
public virtual ApplicationUser User { get; set; }
}
And this is how I'm getting Posts and Users and User is always null here.这就是我获取帖子和用户的方式,用户在这里始终为空。
public Foorum GetById(int id)
{
var forum = _forumDbContext.Forums.Where(f => f.Id == id)
.Include(f => f.Posts)
.ThenInclude(p => p.User)
.Include(f => f.Posts)
.ThenInclude(p => p.PostReplies)
.ThenInclude(r => r.User)
.FirstOrDefault();
return forum;
}
This is how my DbContext looks like:这是我的 DbContext 的样子:
public class ForumDbContext : IdentityDbContext<IdentityUser>
{
public ForumDbContext(DbContextOptions<ForumDbContext> options)
: base(options)
{
}
public DbSet<Foorum> Forums { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<PostReply> PostReplies { get; set; }
}
Startup.cs启动文件
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ForumDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ForumDbContext>();
}
And I've also added app.UseAuthentication();我还添加了 app.UseAuthentication(); app.UseAuthorization();
app.UseAuthorization(); in the Configure method.
在配置方法中。
What am I missing here, why can't I get users from the database?我在这里错过了什么,为什么我不能从数据库中获取用户?
UPDATE更新
Change IdentityUser
to ApplicationUser
in Startup.cs
& ForumDbContext.cs
files, it may help.在
Startup.cs
和ForumDbContext.cs
文件ForumDbContext.cs
IdentityUser
更改为ApplicationUser
,这可能会有所帮助。
As I mentioned in this post , you should add a property UserId
and just set it to the desired User Id
such as _currentUser.Id
.正如我在这篇文章中提到的,您应该添加一个属性
UserId
并将其设置为所需的User Id
例如_currentUser.Id
。 The entity framework will include User
into your model automatically.实体框架会自动将
User
包含到您的模型中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.