【发布时间】:2020-04-21 21:57:00
【问题描述】:
当我尝试让我的用户从表 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; }
}
我要显示的是带有作者信息的帖子
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; }
}
这就是我获取帖子和用户的方式,用户在这里始终为空。
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;
}
这就是我的 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>();
}
我还添加了 app.UseAuthentication(); app.UseAuthorization();在 Configure 方法中。
我在这里缺少什么,为什么我不能从数据库中获取用户?
【问题讨论】:
-
这就是我获取帖子和用户的方式,而用户在这里始终为空:您能否检查数据库并确保具有该 ID 的论坛有一个帖子有用户与该帖子相关联吗?
-
如何映射帖子和用户之间的关系?
-
我也有类似的问题。我看到您的代码有问题的一件事是您有行 services.AddDefaultIdentity
(options ... 这应该是 services.AddDefaultIdentity (options ... 我没有将此作为解决方案发布,因为我没有'还没有 -
投票结束时“需要详细信息或明确性”,因为上述 cmets 中要求的澄清是必不可少的。
标签: c# asp.net-core entity-framework-core asp.net-identity