Here is Index:
It goes through folder and should add entries to database. But when i run it no entries are getting added. Is something wrong with this code?
(Basically code goes through couple folders gets image file and songs under the folder and add to database, but it is not working.)
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();
}
Here are classes and database design too:
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; }
}
You are creating only one movie and song above.
For every folder you overwrite the values in a movie object but never add a new object to your context, you only try to re-add your existing movie.
Also I wouldn’t do this on an index HttpGet method. By the http spec a repeated GET call shouldn’t change the system state each time (hence it should be idempotent)