开发者

Entity framework - what to do if SaveChanges fails and I don't want some changes to be made?

I think I'm running into a common problem: I would like to try to insert an object to the database. If primary key is violated then I would like to abort the insert. (this is an example, the question really applies to any kind of error and any of the CRUD operations)

How can I discard changes made to EF context?

I can't afford recreating it every time something goes wrong.

PS. I know that perhaps I could check if everything is ok eg. by querying the db, b开发者_运维知识库ut I don't like the idea. Db constraints are there for some reason and this way it's faster and I have to write less code.


You can detach inserted entity from ObjectContext. You can also use ObjectStateManager and its method GetObjectStateEntries. In ObjectStateEntry you can modify its state.

The problem is that you are not using technology in supposed way:

I can't afford recreating it every time something goes wrong.

Sure you should because your code doesn't prevent such situations.

PS. I know that perhaps I could check if everything is ok eg. by querying the db, but I don't like the idea. Db constraints are there for some reason and this way it's faster and I have to write less code.

Yes indeed you should check if everything is OK. Calling database to "validate" your data is something that DBAs really like (sarcasm). It is your responsibility to achieve the highest possible validity of your data before you call SaveChanges. I can imagine that many senior developers / team leaders would simply not pass your code through their code review. And btw. in the most cases it is not faster because of inter process or network communication.


Try using DbTransaction.

System.Data.Common.DbTransaction _tran = null;


 _tran = _ent.Connection.BeginTransaction();

_tran .Commit (); //after SaveChanges();

and if theres an exception do a rollback.

_tran.Rollback();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜