简体   繁体   中英

EF Core in .NET 6 console app won't update after SaveChanges()

I just tried to update about 900 items in SQL Server from a console app with Foreach() , but after everything is done, nothing is updated in SQL Server. I don't know why.

I start with debug and see everything work fine, API is ok, all vars are ok. even item.status that I want to get that string is OK! But after calling SaveChanges() , nothing happens to my database.

Here is my code:

Excel_DBContext context = new Excel_DBContext();
var excel = context.Sheets.Where(c => c.Status == null).ToList();
CallWebAPIAsync().Wait();

async Task CallWebAPIAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://jamservice.pna.co.ir/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        Parameters countryList;
        string terminalId;
        string serial;
        HttpResponseMessage response;
     
        foreach (var item in excel)
        {
            terminalId = item.Terminal;
            serial = item.Serial;
            countryList = new Parameters() { TerminalID = terminalId, Serials = serial };

            response = await client.PostAsJsonAsync("services/api/RequestService/BindSerialToSwitch", countryList);

            var resultString = await response.Content.ReadAsStringAsync();

            var resultJson = JsonConvert.DeserializeObject<Excel>(resultString);

            Sheet findTerminal = context.Sheets.First(c => c.Terminal == terminalId);

            if (response.IsSuccessStatusCode)
            {
                item.Status = resultJson.StatusTitle;
                context.SaveChanges();

                Console.WriteLine("Record " + terminalId + " updated");
            }
            else
            {
                Console.WriteLine("Error");
            }
        }
    }
}

My DbSet :

public partial class Sheet
{
    public string? Terminal { get; set; }
    public string? Serial { get; set; }
    public string? Model { get; set; }
    public string? Status { get; set; }
}

Class for API:

public class Excel
{
    public string? Terminal { get; set; }
    public string? Serial { get; set; }
    public string? StatusTitle { get; set; }
}

I found my answer and wanted to share it with you. Because My TerminalId didn't have any duplicate I didn't put any primary key. now I've tested that if I set TerminalId to primary Key in DB and set primary in DBContext and so on... everything works fine. thank you for all your helps. special thanks to @Ryan because of that Code I get the Exception for primary key and without that, there was no exception.

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