如何与ASP身份用户建立一对多关系

joh*_*ohn 4 asp.net-mvc entity-framework-6 asp.net-identity

我使用带有MVC +身份的默认Web应用程序来管理用户,并试图使每个注册用户都制作他的电影列表,并且在登录时只能看到他的列表。

所以,以我为例,我上了电影课

public class Movie
    {
        public int MovieId { get; set; }
        public string MovieName { get; set; }
        public string Year { get; set; }
        public string Genre { get; set; }

        public virtual ApplicationUser ApplicationUser { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

并在ApplicationUser中,我把

public virtual ICollection<Movie> Movies { get; set; }
Run Code Online (Sandbox Code Playgroud)

列出电影列表。

我还制作了一个实体FrameWork MovieController,将Movie用作模型,将ApplicationDbContext用作上下文。

所以我在查询数据库时遇到问题,以使每个用户只能查看他的电影列表,在默认的脚手架中,我在MoviesController的索引操作中得到了此信息

 public ActionResult Index()
        {
            var movies = db.Movies.ToList();
            return View(movies);
        }
Run Code Online (Sandbox Code Playgroud)

如果有人对我的问题有经验,请提供帮助,我们欢迎您提供任何意见,也非常感谢。

Ank*_*wat 5

您需要在影片类ApplicationUserID中添加另一个属性,以在它们之间创建适当的关系,如下所示:

public class Movie
    {
        public int MovieId { get; set; }
        public string MovieName { get; set; }
        public string Year { get; set; }
        public string Genre { get; set; }

        public string ApplicationUserID { get;set; }        
        public virtual ApplicationUser ApplicationUser { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

现在,您可以像这样为用户获取所有电影:

public ActionResult Index()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            string userid = User.Identity.GetUserId();
            IEnumerable<Movie> movies = new List<Movie>();
            if (!string.IsNullOrEmpty(userid))
            {
                movies = context.Movies.Where(x => x.ApplicationUserID == userid);
            }

            return View(movies);
        } 
Run Code Online (Sandbox Code Playgroud)