Does anyone have some good information on the usage of the .SaveChanges() method?
I am experiencing a variety of issues when attempting to use the .SaveChanges() method on my data context object. I am taking data from an existing data source, creating the appropriate EntityFramework/DataService objects, populating those created objects with data, adding those objects to the context and then saving that data by calling .SaveChanges.
The scenarios I've come up with (and the problems associated with them) are as such ... In each scenario I have a foreach loop that is taking data from rows in a DataTable and generating the objects, attaching them to the context as they go. (note: three objects a "member" and two "addresses" that are attached via a SetLink call) - basically this is a conversion tool to take data from one data store and massage it into a data store that is exposed by Data Services.
What is the prefered method of calling .SaveChanges() from a client object when doing a large data load like this? Is there something I'm not getting about how .SaveChanges() works? Can anyone provide more details on how once should be utilizing this function and what (if any) are the limitations to saving data via Data Services? Are there any best practices around the .SaveChanges() method call? Is there any particularly good documentation on the .SaveChanges() method call?
In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.
Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.
Add methods add a new entity to a context (instance of DbContext) which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students. Add(std) adds a newly created instance of the Student entity to a context with Added EntityState.
Use the DbSet. Add method to add new instances of your entity classes. The data will be inserted in the database when you call SaveChanges. The Add, Attach, and Update methods all work on the full graph of entities passed to them, as described in the Related Data section.
I have no big experience in using EntityFramework (just some random experiment), have you tried calling .SaveChanges() every n iterations?
I mean something like this:
int i = 0;
foreach (var item in collection)
{
// do something with your data
if ((i++ % 10) == 0)
context.SaveChanges();
}
context.SaveChanges();
I know it's ugly, but it's the first possible solution i came up with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With