0

MVC4 の膨大な量のチュートリアルで、認証されたユーザーを、そのユーザーに属するデータを含むテーブルにリンクしているのを見たことがありません。私はこれについて高低を見てきましたが、空っぽになりました。

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 のモデルにリンクする方法を説明できますか?

4

1 に答える 1

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);
    }
于 2013-04-09T16:49:55.437 に答える