KJSR
KJSR

Reputation: 1757

C# MVC Entity Framework only saving last row

I have problem with saving records to my db Table from a CSV file. It only seems to save the last record to the database table in the CSV file? I have modified the code multiple times and can't see where I am going wrong?

I have stepped through the code and can see the records are successfully added to the List<location> list and then finally added to the Entity AddRange.

Any suggestion?

public void SaveFilesDetails(DataTable dt)
{
     Location loc = new Location();
     List<Location> list = new List<Location>();
     foreach (DataRow row in dt.Rows)
     {
         loc.Postcode = row["Postcode"].ToString();
         loc.Latitude = row["Latitude"].ToString();
         loc.Longitude = row["Longitude"].ToString();
         loc.County = row["County"].ToString();
         loc.District = row["District"].ToString();
         loc.Ward = row["Ward"].ToString();
         loc.CountryRegion = row["CountryRegion"].ToString();
         list.Add(loc);
     }

     using (PostCodesEntities dataContext = new PostCodesEntities())
     {                
         dataContext.Locations.AddRange(list);                
         dataContext.SaveChanges();
     }
    }

Upvotes: 2

Views: 1921

Answers (2)

pparas
pparas

Reputation: 549

Move the Location loc = new Location(); inside the foreach loop You are overwriting it every time the loop runs.

Upvotes: 3

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

Create new object of Location inside loop. You have declared it outside the loop and it is only getting value of last row so only one object is being stored in the list and only one is being saved.

public void SaveFilesDetails(DataTable dt)
{

     List<Location> list = new List<Location>();
     foreach (DataRow row in dt.Rows)
     {
         Location loc = new Location();
         loc.Postcode = row["Postcode"].ToString();
         loc.Latitude = row["Latitude"].ToString();
         loc.Longitude = row["Longitude"].ToString();
         loc.County = row["County"].ToString();
         loc.District = row["District"].ToString();
         loc.Ward = row["Ward"].ToString();
         loc.CountryRegion = row["CountryRegion"].ToString();
         list.Add(loc);
     }

     using (PostCodesEntities dataContext = new PostCodesEntities())
     {                
         dataContext.Locations.AddRange(list);                
         dataContext.SaveChanges();
     }
    }

Upvotes: 4

Related Questions