0

I want to save all strings to my DB in uppercase. I think the best place to do this is by overriding SaveChanges() on my DbContext. I know I need to call ToUpper() on something but I am unsure on what to call it on.

public override int SaveChanges()
{
    foreach (var entry in ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))
    {
       //do something
    }
    return base.SaveChanges();
}
Kahbazi
  • 14,331
  • 3
  • 45
  • 76
Liam
  • 1,161
  • 12
  • 24
  • 1
    I would do this with CHECK constraints in your database for selected columns, and also with ArgumentExceptions in the corresponding property setters. – David Browne - Microsoft Aug 17 '17 at 14:39
  • I agree with @DavidBrowne-Microsoft - manipulating the data in an overridden SaveChanges() function is a poor choice. I'd opt for transforming them on each property's setter function or even with a trigger to transform them at the database level before I mucked with them at the context. – chambo Aug 17 '17 at 16:07

1 Answers1

0

I'm not sure if it is wise to pollute your Database layer with this constraint. This would limit reusability of your database.

Quite often the definition of structure of the (tables of the) database is separated from the handling of the data in the database, which is done via a separate Database Abstraction Layer.

This separation makes it possible to reuse your database structure for databases with other constraints (for instance, one that allows lower case strings, or a special database for unit tests).

This seperation of concerns is quite often implemented using the repository pattern. This separation makes it possible to change functionality of the database without having to change the structure of the database.

You could also use an existing database that uses lower case strings, as your repository layer could convert everything to upper case before returning queried strings.

So by separating the database from functionality on the data you make it easier to reuse the database for other purposes, and to change requirements without having to change the data in the database: improved reusability and improved maintenance.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116