【问题标题】:Built in Authentication with Custom Class. Code First使用自定义类内置身份验证。代码优先
【发布时间】:2014-01-01 01:33:53
【问题描述】:
MVC 5 带有自己的内置身份验证,这非常棒,正是我所需要的。我不想重新发明轮子,所以我会使用它。如果我需要为用户提供更多信息,我还看到了很多关于如何扩展它的帖子和信息。
我的问题是我需要另一个模型来链接到已登录的用户。想象一个论坛,其中有登录的用户拥有“帖子”。我需要一个 'Post' 类,它与 ASP.NET 完成所有创建工作的用户有关系。
我尝试做类似的事情:
public virtual ApplicationUser CreatedBy { get; set; }
但是这不起作用,而且我不知道如何让它起作用。任何在线教程或示例都专注于 MVC 本身的身份验证元素,或者您创建自己的 dbContext 并在其中完成所有操作的实体框架端。如何将这两者联系起来?
【问题讨论】:
标签:
asp.net-mvc
entity-framework
asp.net-mvc-5
asp.net-identity
【解决方案1】:
要从另一个类添加对您的应用程序用户的引用,您可以尝试以下操作:
public class Post{
public int Id { get; set;
public string Name { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
}
并在您的控制器中创建操作(或您正在创建新帖子的位置):
(为清楚起见,为用户管理器等添加了代码行)
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();