Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
- This code saves my data to the database

- This app records the time spent on each day of the month

- They write to the database in sql server, using EF

- The problem is just that I would like them to overwrite instead of writing more


Controller:
List<Karta_Model> objNextKartaModel = new List<Karta_Model>();
for (int i = 0; i < liczbaDni; i++)
{
     var modelNext = new Karta_Model()
     {
     Login = userName,
     Rok = numerRoku,
     Miesiac = numerMiesiaca,
     DzMiesiaca = modelKarta.Model1[i].DzMiesiaca.Value,
     DzTygodnia = modelKarta.Model1[i].DzTygodnia,
     Rozpoczecie = modelKarta.Model1[i].Rozpoczecie
     ....
     };

objNextKartaModel.Add(modelNext);
            

await _ecpContext.Karta.AddRangeAsync(objNextKartaModel);
await _ecpContext.SaveChangesAsync();

}


'Id' in In sql server:

> [Id] [int] IDENTITY(1,1)

- I came up with the idea to extract the first row ID from the previously saved database

var nrIdBase = _ecpContext.Karta.FirstOrDefault(f => f.DzMiesiaca == 1 && f.Miesiac == numerMiesiaca && f.Rok == numerRoku && f.Login == userName).Id;


- but I don't know how to use it

What I have tried:

- I tried something this way

for (int i = 0; i < liczbaDni; i++)
{
     var modelNext = new Karta_Model()
     {
     Id = nrIdBase +i,
     Login = userName,
     Rok = numerRoku,
     Miesiac = numerMiesiaca,
     DzMiesiaca = modelKarta.Model1[i].DzMiesiaca.Value,
     DzTygodnia = modelKarta.Model1[i].DzTygodnia,
     Rozpoczecie = modelKarta.Model1[i].Rozpoczecie
     ....
     };
}



Error:
> InvalidOperationException: The instance of entity type 'Karta_Model' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.




- anyone have an idea how to do this?

- How to overwrite saved data once?
Posted
Updated 8-Feb-20 15:43pm

1 solution

You read a record or records (that were previously "saved"), update any fields, then save:

c# - How to update record using Entity Framework 6? - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900