MichaelMcCabe
MichaelMcCabe

Reputation: 523

Built in Authentication with Custom Class. Code First

MVC 5 comes with its own built in authentication which is great and exactly what I need. I don't want to re-invent the wheel, so I will use that. I have also seen lots of posts and information on how to extend that if I need more information for a user.

The question I have is that I need to have another Model that links to the user that is logged in. Imagine a forum where there are logged in users who have 'Posts'. I need a 'Post' class with a relationship to the user that ASP.NET has done all the work to create.

I tried doing something like:

public virtual ApplicationUser CreatedBy { get; set; } 

However that didn't work, and I don't know enough to figure out how I get it to work. Any tutorials or examples online focus on the authentication element of MVC on its own, or the entity framework side where you make your own dbContext and go off to do everything in there. How can I link these two up?

Upvotes: 1

Views: 863

Answers (1)

Indregaard
Indregaard

Reputation: 1195

To add a reference to your applicationuser from another class you can try something like this:

public class Post{
     public int Id { get; set; 
     public string Name { get; set; }

     public virtual ApplicationUser CreatedBy { get; set; } 
}

And in your controller create action (or where you are creating your new Post): (Added code lines for usermanager etc for clarity)

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();

Upvotes: 1

Related Questions