I've written a group of classes that access the database to map DB data to objects. Other programmers will be manipulating the objects, and so I'm trying to make it as difficult as possible for them to do anything that would break any contracts. One of the things that would help is to make the id (primary key) read-only. However, at some point or another, an id will need to be assigned to the object.
In Java, I'd simply group all of the DB access classes into a package, and declare a couple of methods in my abstract class
public int getId() { return id; }
default void setId(int id) { this.id = id; }
so that only members of the same package could set the id. I'm having trouble coming up with a good design in C#, though. Currently, the constructor to DB objects takes an int?
that should be set to null
before an object has persisted to the DB. If id
is not set to null when instantiated outside of the DB-access classes, some contracts might be broken. I'd make a second constructor that doesn't take an argument for the id for access outside of the DB-access classes, but I'm running into the same problem with restricting access appropriately: if the constructor is accessible to classes in the same namespace / partial class, it's accessible to the assembly.
Does anyone have any good design strategies for handling a situation like this with C#?