I recently started using Entity Framework, and it has been kind of a pain to check if I really need to add new records to the database or not.
If the Entity I need to add to the database is already on it, I will know, because I do a query before inserting it, and if it exists, then I keep that instance because I need to use it in some relationships.
Let's suppose my entity name is Book.
The problem comes when an entity isn't in the database, and I do:
Book b = //...
modelContainer.AddToBooks(b);
I could easily do:
modelContainer.SaveChanges()
everytime I add a new entity (no matter what entity it is), and this will work fine, because as I'm inserting one kind of entry at a time, and checking if it already is in the database, I won't have duplication problems.
But what if I want to avoid calling SaveChanges() so often?
In this question: Is is possible to check if an object is already attached to a data context in Entity Framework?, the author of the question provides a method that kind of helps me in my case, but it does not work if I Add the object to the context instead of Attaching it.
My question (maybe two, but very related) is: What is the difference between Add and Attach and how can I solve my problem?
Edit:
Here is an example of the problem I'm having.
I have an entity Result that has a relationship with two more entities: Trainer and Horse.
I get the data from an external source, so I have to create manually all the entities.
Everytime I need to insert a new Trainer, I do:
var trainer = Trai