Home > Software engineering >  context.savechanges saves data from back
context.savechanges saves data from back

Time:02-24

I have problem with saving data in my database. For example I have this code:

if (!context.Kategorijas.Any())
{
    context.Kategorijas.Add(new Kategorija { Naziv = "Hrana" });
    context.Kategorijas.Add(new Kategorija { Naziv = "Igracke" });
    context.Kategorijas.Add(new Kategorija { Naziv = "Odjeca" });
    context.Kategorijas.Add(new Kategorija { Naziv = "Higijena" });
    context.Kategorijas.Add(new Kategorija { Naziv = "Oprema" });
}

context.SaveChanges();

My problem is that this data is saved in database, but from back, like this:

Id 1 - Oprema
Id 2 - Higijena
Id 3 - Odjeca
Id 4 - Igracke
Id 5 - Hrana

How to fix this? Thank you.

CodePudding user response:

you will have to use save changes after each add, think twice do you really need it

     if (!context.Kategorijas.Any())
        {
         
             context.Kategorijas.Add(new Kategorija { Naziv = "Hrana" });
             context.SaveChanges();
            context.Kategorijas.Add(new Kategorija { Naziv = "Igracke" });
               context.SaveChanges();

           // and so on
        }
  • Related