cgatian
cgatian

Reputation: 22994

MVC4 Linking Models To SimpleAuthentication Class

In the vast amount the tutorials for MVC4, I never see them link the authenticated user to a table containing data that belongs to that user. I've looked high and low on this and have come up empty.

Take for example a table of Note, each user would store a Note to the database. How can I take my simple class and link the authenticated user to it? Below is as close as I feel I've gotten without results.

 public class Note
    {
        public int NoteId { get; set; }
        [ForeignKey("UserId")]
        public virtual UserProfile CreatedBy { get; set; } 
        public string Description { get; set; }
    }

Anyone have a good tutorial link or can explain how I should be linking my authenticated user (using simpleauthentication) to models in ASP.net MVC4?

Upvotes: 0

Views: 204

Answers (1)

Komengem
Komengem

Reputation: 3764

Change your entity to:

public class Note
{
    [Key]
    [ForeignKey("UserProfile"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserId{ get; set; }

    public virtual UserProfile UserProfile { get; set; }

    public string Description { get; set; }
}

Then, in your Note controller or whatever controller you have creating your Notes:

    [Authorize]//Place this on each action or controller class so that can can get User's information
    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(CreateViewModel model)
    {
        if (ModelState.IsValid)
        {
            var db = new EfDb();                
            try
            {                   
                var userProfile = db.UserProfiles.Local.SingleOrDefault(u => u.UserName == User.Identity.Name)
                                ?? db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);
                if (userProfile != null)
                {
                    var note= new Note
                                        {
                                           UserProfile = userProfile,
                                           Description = model.Description 
                                        };                        
                    db.Notes.Add(note);
                    db.SaveChanges();
                    return RedirectToAction("About", "Home");
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                throw;
            }
        }            
        return View(model);
    }

Upvotes: 1

Related Questions