2013-04-09 45 views
0

在大量的MVC4教程中,我从不会看到它们将认证用户链接到包含属于该用户的数据的表。我看上去很高,并且已经空了。MVC4将模型链接到SimpleAuthentication类

拿一个Note的表为例,每个用户都会把一个Note存储到数据库中。我怎样才能带上我的简单课程并将认证用户链接到它?下面就像我觉得我没有结果一样。

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

任何人有一个很好的教程链接,或可以解释如何我应该(用simpleauthentication)来连接我的身份验证的用户在ASP.net MVC4模式?

回答

1

你的实体更改为:

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; } 
} 

然后,在你的注意控制器或任何控制器已创建注释:

[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); 
    } 
+0

你介意加入一个链接,下载该项目?我很想知道你是如何创建EfDB()的。还有,为什么你不需要指定UserId部分?它看起来像当你设置userProfile,它只是工作。这是解决这个问题的常见方式吗? – cgatian 2013-04-09 17:19:48

+0

另外你为什么要查询db.UserProfiles.Local? – cgatian 2013-04-09 17:22:47

+0

没有项目,我在这里构建这个。我假设你有一个EfDatabase类。我使用了'UserProfile.Local'来避免不必要的旅程返回到数据库。它是一种获取已登录的User'Watch MVC4视频的'UserId'的方式,以便从链接中了解更多信息。 http://pluralsight.com/training/Au​​thors/Details/scott-allen – Komengem 2013-04-09 18:32:28