Click here to Skip to main content
15,894,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Please kindly assist me with trying to fix my import data from excel to a database using Entity Framework along with MVC.

The error i have been getting states that the following code is UNREACHABLE
for (int row = 2; ws.Cells[row, col].Value != null; row++ )
.

So because of this error, whenever I run my code, my FOR code is been skipped.

What I have tried:

public ActionResult Import()
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                try
                {
                    using (var p = new ExcelPackage(file.InputStream))
                    {
                        ExcelWorksheet ws = p.Workbook.Worksheets[1];
                        int col = 1;

                        //Insert records to database table.
                        EntertainmentEntities entities = new EntertainmentEntities();

                        for (int row = 2; ws.Cells[row, col].Value != null; row++ )
                        {
                            entities.Music.Add(new Music
                            {

                                Artist = ws.Cells[row, 1].Value.ToString(),
                                Song = ws.Cells[row, 2].Value.ToString(),
                                Genre = ws.Cells[row, 3].Value.ToString(),
                                MusicDate = (int)ws.Cells[row, 4].Value
                               

                            });
                            
                            entities.SaveChanges();
                            return View("Index");
                        }


                    }
                }
                catch
                {
                    ViewBag.Message = "Error";
                }

            }
            else
            { }
            return View("Import");
        }
Posted
Updated 11-Sep-18 5:34am
Comments
ZurdoDev 11-Sep-18 8:07am    
Debug the code and find out why. Pretty easy.

1 solution

for (int row = 2; ws.Cells[row, col].Value != null; row++ )
{
    entities.Music.Add(new Music
    {
        ...
    });
    
    entities.SaveChanges();
    return View("Index");
}

You have a return statement inside your for loop. As a result, the loop will execute once and immediately return.

Move the SaveChanges and return lines outside of the for loop:
C#
for (int row = 2; ws.Cells[row, col].Value != null; row++ )
{
    entities.Music.Add(new Music
    {
        ...
    });
}

entities.SaveChanges();
return View("Index");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900