Should an entity access the Service Layer and execute Update/Save methods?

258 views Asked by At

My application requirements: if any property is changed by the user - like entering data into a textbox and then leaving the textbox - it must be updated immediately to the database.

I using WPF with MVVM design pattern. All my entities implement INotifyPropertyChanged. If any property of a CUSTOMER changes I do

Customer.cs

customerService.UpdateCustomer(this);

Should an entity really update itself? Or induce its own update into the database?

I mean how else could I do an immediate upate of a property if not within the entity ?

1

There are 1 answers

3
Frederik Gheysels On

An entity should not update itself; another service (repository) should do that. You can induce the repository that the entity should be updated, by subscribing to the PropertyChanged event of the entity. In the eventhandler, you can make sure that your entity is updated:

Customer c = new Customer();

c.PropertyChanged += (s, e) => customerService.UpdateCustomer(c);

But, on a sidenote, I think it is a strange requirement that your entity should be changed whenever a property changes. This means that transactions are quite useless. I mean, you have no real 'unit of work', where all changes should be committed, or should not be persisted at all ? Next to that, it also results in lots of roundtrips to the database.