Reputation: 45
I'm fairly new to oop and programming in general, but one thing that i don't understand if when working with relational databases like in EF core you should have immutable objects or not.
If i set properties with private setters, so that i can only assign values when creating these objects, how can I change their state?
Do i create a new empty objects and then copy every single properties that needs to stay the same and update only some of them with myObject.property = updatedValue
?
Do i use a factory to instanciate that object with the correct values?
Isn't this violating oop principles by having public setters?
I have encounter this problem for example when having a server and a client that exchange data and the client do somework on this data. When the data returns, with a dto class, i still need to update the related data that is saved in the database.
Upvotes: 4
Views: 5104
Reputation: 451
EF Core does support immutability, more specifically it can utilize the constructors of your entities. This enables you to create purely immutable properties for your entities (only getters, which generate readonly backing fields), or even the whole entity can be immutable.
Some points to consider:
I have elaborated in more detail in this blog post.
Upvotes: 7
Reputation: 74
If you are talking immutable objects, then no you will not update their values, and you will have to create a whole new instance if that object changes, that is what makes them immutable. But if you are trying to encapsulate an entity that can change state, and would like to change the values of that entity, then you would typically have command methods on that object that will change the values of the properties to provide the encapsulation, I believe you are shooting for.
In the past when I have went a similar route using an ORM, I had data entities (classes) at the data layer that had public getters and setters, and the ORM would instantiate the objects and populate them without issue, then my repository would map them to the business layer classes that had private setters. I believe I used automapper to do this, and it didn't have a problem mapping with the private setters.
Then from a UI interaction perspective, to update the models, the business entities would have specific command methods rather than just an overarching "update" method. Things like "UpdateAddress", "makePayment", and such. These methods would update the appropriate private variables of the class and filter down into the data entities and then to the database.
I do think a lot of this can be overkill depending on what you are working on, a lot of applications are mostly CRUD applications, and don't require a lot of business rules. In that case I personally wouldn't worry about private setters and whatnot, unless it makes sense for you.
Upvotes: 0