How to create different data with each different user?

时间:2015-09-01 21:38:36

标签: asp.net-mvc entity-framework asp.net-identity

Im using asp.net entity framework and asp.net identity, and what im trying to do is to register with some account and to make some data with user#1(agentmi6) like:

and then log in with user#2(john) and make some data with this user:

so my main problem is how to make users view only their created data.

1 个答案:

答案 0 :(得分:1)

在我的电影模型中,我添加了与应用程序用户的关系

public class Movie
    {
        [Key]
        public int MovieId { get; set; }
        public string Name { get; set; }
        public string Year { get; set; }
        public string Genre{ get; set; }


        public string ApplicationUserID { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

然后在MoviesController中添加了此查询以获取当前注册用户创建的所有电影:

 public ActionResult Index()
        {
            var currentUser = User.Identity.GetUserId();
            var movies = db.Movies.Where(x => x.ApplicationUserID == currentUser);
            return View(movies);
        }

并在创建影片时在控制器的“创建”操作中,我将当前用户添加到该影片

public ActionResult Create(Movie movie)
        {
            if (ModelState.IsValid)
            {
                movie.ApplicationUserID = User.Identity.GetUserId();
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(movie);
        }

在所有的MoviesController视图中我删除了应用程序用户html,因为我不想在索引和创建电影时显示。

最后我得到了我想要的东西。

使用用户a@a.com登录并制作一部只有他可见的电影,

和第二个用户v@v.com只能看到他的电影。