0

这是索引:它通过文件夹并应将条目添加到数据库。但是当我运行它时,没有添加任何条目。这段代码有问题吗?(基本上代码通过几个文件夹获取文件夹下的图像文件和歌曲并添加到数据库,但它不起作用。)

public ActionResult Index()
        {            
            DemoDb db = new DemoDb();
            var movies = new List<SongModel>();
            MovieModel movie = new MovieModel();
            SongModel song = new SongModel();
            //Function to get all the folders present in that particular location,Use
            var folders = Directory.GetDirectories(Server.MapPath("~/Content/themes/base/songs"));

            foreach (var folder in folders)
            {
                movie.MovieName = new DirectoryInfo(folder).Name;
                string[] files = Directory.GetFiles(folder);
                string img = string.Empty;
                var list = new List<string>();
                foreach (var file in files)
                {
                    if (Path.GetExtension(file) == ".jpg" ||
                        Path.GetExtension(file) == ".png")
                    {
                        movie.Image = Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file);
                    }
                    else
                    {
                        song.MovieId = movie.MovieId;
                        song.Song = Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file);                        
                    }     
                }
                db.movies.Add(movie);
                db.songs.Add(song);
                db.SaveChanges();
            }              
            return View();
        }

这里也是类和数据库设计:

public class MovieModel
    {
        [Key]
        public int MovieId { get; set; }
        public string MovieName { get; set; }
        public int SongId { get; set; }
        public string Image { get; set; }
    }
    public class SongModel
    {
        [Key]
        public int SongId { get; set; }
        public int MovieId { get; set; }
        public string Song { get; set; }
    }
4

1 回答 1

0

您只在上面创建了一部电影和一首歌曲。对于您覆盖电影对象中的值但从未将新对象添加到上下文中的每个文件夹,您只尝试重新添加现有电影。此外,我不会在索引 HttpGet 方法上执行此操作。根据 http 规范,重复的 GET 调用不应每次都更改系统状态(因此它应该是幂等的)

于 2012-10-14T05:06:49.700 回答