在哪一层我应该确定某物是否存在

huangapple go评论69阅读模式
英文:

At what layer i should determine if something does not exist

问题

应该在将评论插入数据库之前,在应用程序中使用SELECT查询检查主题是否存在吗?或者,应该依赖数据库约束,并处理如果主题不存在将抛出的异常?

英文:

Suppose I have a Comment entity defined as follows:

public class comment 
    {
        public int Id { get; set; }
        public int TopicId { get; set; }
        public string Text { get; set; }
    }

The TopicId property represents a foreign key referencing the Topics table.

My question is, should I check in my application (using a SELECT query) whether the topic exists before inserting the comment into the database? Alternatively, should I rely on the database constraint and handle the exception that will be thrown if the topic does not exist?

答案1

得分: 1

数据处理逻辑应该在数据库上处理。

通常,将这种逻辑处理在较低级别(靠近表示实体的数据库表)可以:

  1. 减轻外部进程影响CRUD(创建-读取-更新-删除)操作的风险,例如,在执行SELECT检查外键之后但在将“comment”实体插入数据库之前,如果数据库更新了。

  2. 符合“关注点分离”的原则,将数据管理的负担移到“模型”上,而不是“控制器”(您称之为“应用程序”)。有关此原则和“模型-视图-控制器”架构的更多信息,请查看The Overflow博客中的今天的条目:模型-视图-控制器

英文:

Data processing logic should be handled on the database.

In general, handling this logic at a 'lower' level (closer to the database table representing the entity)

  1. mitigates the risk of external processes affecting your CRUD (Create-Read-Update-Delete) operations, such as if your database is updated after you perform a SELECT check for the foreign key but before you insert the comment entity into the database.

  2. aligns with the principle of 'Separation of Concerns,' loading the burden of data management onto the 'model' and off of the 'controller' (what you refer to as your 'application'). For more on this principle and the 'Model-View-Controller' architecture, check out today's entry in The Overflow blog: Model-View-Controller

答案2

得分: 0

如果在插入之前检查TopicId,则可能存在记录或不存在,但如果存在,则必须调用数据库两次,首先进行验证,然后进行插入,还必须为验证编写额外的代码,通过依赖数据库外键约束,您只需关注异常处理。

英文:

If you check TopicId before inserting then it may be possible that the record may exist or not but if exist then you have to call Database two times first validation and then insertion, also you have to code extra for validation,
by relying on Database foreign key constraint, you just have to focus on exception handling.

huangapple
  • 本文由 发表于 2023年5月22日 21:17:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定