2013-04-09 41 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