C# MVC4将模型链接到SimpleAuthentication类

C# MVC4将模型链接到SimpleAuthentication类,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,在MVC4的大量教程中,我从未看到它们将经过身份验证的用户链接到包含该用户数据的表。我在这件事上到处张望,结果一无所获 以注释表为例,每个用户都会将注释存储到数据库中。如何获取我的简单类并将经过身份验证的用户链接到它?下面是我感觉到的没有结果的接近 public class Note { public int NoteId { get; set; } [ForeignKey("UserId")] public virtual UserPr

在MVC4的大量教程中,我从未看到它们将经过身份验证的用户链接到包含该用户数据的表。我在这件事上到处张望,结果一无所获

以注释表为例,每个用户都会将注释存储到数据库中。如何获取我的简单类并将经过身份验证的用户链接到它?下面是我感觉到的没有结果的接近

 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中的模型

将您的实体更改为:

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

你介意添加一个链接来下载这个项目吗?我很想知道您是如何创建EfDB()的。还有,为什么不必指定UserId部分?看起来,当您设置userProfile时,它就正常工作了。这是解决这个问题的一种非常常见的方法吗?还有为什么要查询db.UserProfiles.Local?没有项目,我就在这里构建了这个。我假设您有一个EfDatabase类。我使用了
UserProfile.Local
,以避免不必要的返回数据库的过程。这是一种获取已登录用户的
UserId
的方法,可以观看MVC4视频,从链接中了解更多信息@cgatian Oh和我使用
UserProfile=UserProfile
指定了
UserId
。这是一种有效的做法,因为我们在
Note
中有
userProfile
属性……如果这对您有效,我将非常感谢您的邀请。