Entity Framework - how to come with failure when saving data
let's suppose the situatio开发者_运维知识库n looks like this: I have one object context in my app and I download 15k records from the db (like 15k invoices). User picks one and makes some changes to it. I call SaveChanges() and it fails for some reason (doesn't matter what reason).
Now the context that was used can't perform any save because it wasn't able to save those changes. What should I do to make it work?
Another scenario is that I use a separate context for making changes. If saving fails then nothing happens - I discard the context and that's it. The problem that arises is: how to merge changes back to the main context? (without downloading 15k records once again)
Idea of downloading 15k records smells pretty bad but lets assume you must do it. The scenario you must follow to make this work should look like:
- Create first context for data retrieval.
- Execute query to get your 15k records. Execute query as
NoTracking
(MergeOption
ofObjectQuery
)! It will improve performance because these records will never be used in context again. - Close first context
- User picks and invoice = create deep clone of the invoice and attach it to a new context (in case of WPF or WinForm application)
- User saves changes and exception is fired. If you want to deal with exception somehow you still have only context with single invoice. You can dispose context and return to your original set of unaffected records.
- If the entity is saved you should merge changes back to list because your entity in 15k records will not be updated automatically.
精彩评论