Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

c# - SaveChanges vs. AcceptAllChanges in Entity Framework

What's the difference between, _context.SaveChanges and _context.AcceptAllChanges(), is the AcceptAllChanges() is sort of reloading data from Database or rolling back (discarding) changes made by the user when he didn't use SaveChanges()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ObjectContext.AcceptAllChanges Method - MSDN

If the SaveChanges method was called and the AcceptAllChangesAfterSave was not specified, the user must call the AcceptAllChanges method. The AcceptAllChanges method is useful in the scenario where a transaction has failed and a user wants to retry.

You may see this: http://blogs.msdn.com/b/alexj/archive/2009/01/11/savechanges-false.aspx

If you call SaveChanges() or SaveChanges(true),the EF simply assumes that if its work completes okay, everything is okay, so it will discard the changes it has been tracking, and wait for new changes.

Unfortunately though if something goes wrong somewhere else in the transaction, because the EF discarded the changes it was tracking, we can’t recover.

This is where SaveChanges(false) and AcceptAllChanges() come in.

SaveChanges(false) tells the EF to execute the necessary database commands, but hold on to the changes, so they can be replayed if necessary.

Now if the broader transaction fails you can retry the EF specific bits, with another call to SaveChanges(false). Alternatively you can walk through the state-manager to log what failed.

Once the broader transaction succeeds, you simply call AcceptAllChanges() manually, and the changes that were being tracked are discarded.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...