简体   繁体   中英

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();
     }
    }

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();
     }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM