这是索引: 它遍历文件夹,应该向数据库添加条目。但是当我运行它时,没有任何条目被添加。这段代码有问题吗? (基本上代码通过几个文件夹获取图像文件和文件夹下的歌曲并添加到数据库,但它不起作用。)
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; }
}
答案 0 :(得分:0)
您正在制作上面只有一部电影和歌曲。 对于每个文件夹,您都会覆盖影片对象中的值但从不向上下文添加新对象,您只需尝试重新添加现有影片。 我也不会在索引HttpGet方法上这样做。通过http规范,重复的GET调用不应该每次都改变系统状态(因此它应该是幂等的)