MVC5自带了自己的内置身份验证,这很棒,也正是我需要的。我不想重新发明轮子,所以我将使用它。我还看到了很多关于如何扩展的帖子和信息,如果我需要为用户提供更多信息的话。
我的问题是,我需要有另一个模型,链接到已登录的用户。想象一下一个论坛,其中有登录的用户,他们有“帖子”。我需要一个'Post‘类与用户的关系,ASP.NET已经做了所有的工作来创建。
我试着这样做:
public virtual ApplicationUser CreatedBy { get; set; }
然而,这并不起作用,我也不知道如何让它起作用。任何在线教程或示例都集中在MVC本身的身份验证元素上,或者在实体框架方面,您可以创建自己的dbContext,然后在那里做所有的事情。我怎样才能把这两者联系起来呢?
发布于 2013-12-13 12:47:00
要从另一个类添加对您的应用程序用户的引用,您可以尝试如下所示:
public class Post{
public int Id { get; set;
public string Name { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
}
并在您的控制器中创建操作(或在您创建新帖子的位置):(为清晰起见,为usermanager等添加了代码行)
var post = new Post { Name = "My new post" }
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currenApplicationUser = userManager.FindById(User.Identity.GetUserId());
var currentUser = db.Users.Find(currenApplicationUser.Id);
post.CreatedBy = currentUser;
db.Posts.Add(post);
db.SaveChanges();
https://stackoverflow.com/questions/20563848
复制相似问题