英文:
Is it a bad practice to use mutable records for database entities?
问题
C# 9.0引入了记录(records)以支持更多面向数据的结构。我想将其用于与某种ORM(如Dapper)一起使用的实体对象,因为它们提供了许多有用的功能,如基于值的相等性。我相信一个建议或良好的做法是保持记录为不可变的(init only),但这将意味着在业务逻辑中更改实体时需要进行大量的复制操作。在数据库实体中使用可变记录是否是可接受的做法?
英文:
C# 9.0 introduced records for more data oriented structures. I would like to use them for entity-objects that are used with some sort of ORM (like Dapper), because they provide a lot of useful functionality like value based equality. I believe one suggestion or good practice is to keep records immutable (init only), but this would mean a lot of copy operation when altering the entities in the business logic. Is it an acceptable practice to use mutable records for database entities?
答案1
得分: 1
这是我认为问题所在的地方: 你想使用可变记录,因为你想在业务逻辑中更改数据库实体。这立即使这些对象不能被视为纯数据库实体。现在你应该把它们看作是领域实体,恰好与你的数据库对象一一匹配。
这样做是否有错? 不一定。但这会紧密地将你在应用层中处理这些对象的方式与它们在数据库中存储的方式耦合在一起。有很多情况下这并不是一个好主意。领域和持久化是两个不同的世界。所以,你可能需要考虑一下。
那么,你是否应该为领域实体使用可变记录? 我认为这样做没有问题。但它可能/不应该止步于此。典型的领域实体预计会在其中封装一些逻辑(行为)。这至少是领域驱动设计的本质。因此,你的记录中不仅会有可变属性,还会有自定义定义的方法。同样,在你想要从记录中获得的自动生成的代码中受益的情况下,我认为这样做没有问题。但就个人而言,我只会在绝对需要时才这样做。否则,我会使用类。
英文:
Here is where I think the problem is: You want to use mutable records because you want to alter your database entities in the business logic. This immediately disqualifies these objects from being pure database entities. You should now look at them as domain entities that happen to have 1:1 matching with you database objects.
Is this wrong? Not necessarily. But it tightly couples how you handle these objects in your application layer with how they are stored in your database. There are many cases when this is not a good idea. Domain and Persistence are two different worlds. So, you may need to think about this.
Now, should you use mutable records for domain entities? I don't see a problem doing this. But it might/should not end there. Typical domain entities are expected to have some logic (behaviour) encapsulated in them. That is at least the essence of domain-driven design. So, not only will you have mutable properties in your records, but you will also have custom-defined methods. Again, I don't see a problem doing this in the cases where you want to benefit from the auto-generated code you get with records. But personally, I will only do it when it's absolutely needed. Otherwise, I will just use classes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论