I am reading some data from a database using entity framework(reads successfully)and modifying the entity works perfectly but it does not save changes to the database.
The code reads 15 records but it does not iterate through them all inside the loop. It goes through the first element of the list and stops at DbContext.SaveChanges() without saving changes.
Any idea what is wrong with my code?
public async Task LinkCardAsync(postcardContext DbContext)
{
HttpClient cons = new HttpClient();
cons.BaseAddress = new Uri("http://cbsswfint01:53303/");
cons.DefaultRequestHeaders.Accept.Clear();
cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
using (cons)
{
try
{
var cardsData = DbContext.MasterpassBulkLoad.Take(15).ToList();
foreach (var cardDetails in cardsData)
{
Console.WriteLine(cardDetails.Msisdn);
Console.WriteLine(cardDetails.Status == null);
HttpResponseMessage res = await cons.PostAsJsonAsync("api/Cardmanagement/CardLoad", cardDetails);
cardDetails.Status = (int)res.StatusCode;
Console.WriteLine("before save");
DbContext.SaveChanges();
Console.WriteLine("After Save");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
_logger.LogError(ex.InnerException.StackTrace);
}
}
}
public void Run()
{
using (var DbContext = new postcardContext())
{
_cardLinkService.LinkCardAsync(DbContext);
}
Console.ReadKey();
}
DbContext.SaveChanges()outside the foreach loop and if it's not still saving try a for loop and updateStatususingcardsData.Get(index).Status = ...