How can i ignore a DbUpdateConcurrencyException with my Entity Framework code?

后端 未结 2 647
生来不讨喜
生来不讨喜 2021-02-14 07:43

Is there any way I can tell EF to not worry about the number of rows a DELETE or UPDATE do or don\'t do?

I\'m trying to delete

相关标签:
2条回答
  • 2021-02-14 08:29

    I think the behavior of EF is correct - simply you must execute commands only for objects which are present in DB. It is not for scenarios like: "I will try it and we will see...". If you can't be sure that object exists in DB and you don't want to do round trip (which I think is the best idea because deleting detached object can have several other pitfalls especially if object participates in independent associations) you should use DbContext.Database.SqlCommand and run store procedure.

    The correct way to handle DbUpdateConcurrencyException is described here => After each exception you should resolve confilicts (in your case it means remove problematic entity from DbContext) and execute SaveChanges again.

    0 讨论(0)
  • 2021-02-14 08:32

    You can in fact ignore these kinds of issues by setting:

    db.Configuration.ValidateOnSaveEnabled = false;

    Where db is the DbContext instance.

    Obviously you should know what you're doing when you do this, but then again, most approaches to updating a database that are not EF don't have any change tracking/validation and just issue update/insert/delete to the database naively without checking anything first, so you're basically just telling EF to behave more like that.

    0 讨论(0)
提交回复
热议问题