Entity Framework is inserting duplicate to each Savechanges

Asked

Viewed 46 times

0

Hello, I am using a technique to be able to insert many entities in the database, I am using C#, Entityframework and SQL server.

Example

List<Editora> editoras = new List<Editora>();
Editora editora1 = new Editora() { ID = 1, nome = "Teste" };

foreach(Livro livro in livros) {
    editora.livros.Add(livro);
}

Now I’m going to put it in the database as follows

context.livros.AddRange(livros);

This approach works perfectly, but assuming there are 1,000,000 books, it takes a long time and most of the time exceeds my RAM memory limit.

So I used the technique batch-Insert found in this post

This way I insert every 100 for example and call the function SaveChanges.

The problem is that by inserting the notes from Publisher 1, and then inserting the notes from Publisher 2, all the notes from Publisher 1 are re-inserted.

I find this very strange because I recreated the context and added only the notes of Publisher 2 to the new context. How Etity Framework is adding everything new from the old context?

  • 1

    You need to see what you’re doing, the part that really matters hasn’t been put in.

  • If it is the same as the example try using context = new Mydbcontext(); in a block using

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.