Enforcing Database Constraints In Application Code

后端 未结 2 1301
悲哀的现实
悲哀的现实 2021-01-14 22:51

I\'m working on my first real asp.net web application and I\'m kind of stumped on the best place and method to trap and handle database constraint violations. Suppose I hav

相关标签:
2条回答
  • 2021-01-14 23:19

    The latter answer is correct. What would be the purpose of using database constraints if you try and do everything first in your front end application?

    The entire point of constraints is to have a central location (the DB server) that handles as much of the data validation as possible, in a consistent fashion, regardless of how/where the data gets there. Writing the same logic all over again in your front end application is redundant, and needlessly complex. What if something changes in the constraint in the DB (something your app thinks should be valid no longer is)? You get an exception anyway.

    Let the DB handle validating constraints, and handle the exceptions in your code. This allows all means you use to access and update the data to be consistent, since the DB handles it. If something changes, you update the DB with the new constraints and your apps are automatically in synch.

    0 讨论(0)
  • 2021-01-14 23:21

    I agree that it is the latter given your description of how you are using the database. It is really important to realize that even if you made a call from your business layer to validate every single possible constrain violation before doing an update/insert, a split second later the database state could change because of requests of other users and your update/insert could still fail.

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