I have a class with several fields.
public readonly byte Id;
public bool Active { get; set; }
public List<Group> Groups { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Gender Gender { get; set; }
public string IdCard { get; set; }
public List<string> PhoneNumbers { get; set; }
public string Address { get; set; }
public string PicturePath { get; set; }
public string Comments { get; set; }
In the database, I have a table with corresponding fields. I want that whenever I change the value of this fields, the corresponding field in the table will be updated too.
My first instinct was to do so in the set
accessor, but I have read that "property getters are expected to be fast and idempotent", and database querying is not always fast.
So I thought maybe to create a method UpdateDatabase()
which should be invoked by the user of the object whenever he changes the value of one of those properties. Then the method updates the database with the new values. But it's very tedious...
Which approach is better? Would you suggest another approach completely?
-
3Make your class observable. Fire a property changed event and have your listener decide what to do. It keeps the db logic out of your class.RubberDuck– RubberDuck2016年05月17日 13:57:47 +00:00Commented May 17, 2016 at 13:57
-
+ R.D's comment. This addresses the explicit issue of "... whenever he [the user] changes [via a GUI, I assume] the value of ... properties." How the DB is wired-in is a separate issue.radarbob– radarbob2016年05月17日 17:03:06 +00:00Commented May 17, 2016 at 17:03
2 Answers 2
I would recommend an ORM-System. Because you tagged your question with C# I'd say a good variant would be using Entity Framework with a Code First approach.
This will allow you to change your code and automatically apply the changes to the Database. Depending on your configuration you can allow the Database to automatically update the Db-Model or to invoke the update via the command line directly in Visual Studio (similar to your UpdateDatabase() approach). The latter will allow you a finer control over your Versioning of the DB-Model, but for a simple project the first version should also be okay (and match more exactly your question).
For a simple beginners tutorial have a look at this tutorial
-
+1 - very good answer. This is one reason they created ORM in the first place.JeffO– JeffO2016年05月17日 16:50:17 +00:00Commented May 17, 2016 at 16:50
But it's very tedious...
Tedious, perhaps, but the updates is then under your [code's] control and can be properly Transactional, unlike "random" changes popping down to the database as and when any item changes.