Search code examples
wcfdeserializationpipeline

Trimming Spaces on Deserialization in WCF Services


My requirement is to put a generic way to ensure that no leading/trailing spaces are stored in the Database. Our architecture is WCF->Business Logic Managers->Generic Repository->Entity Framework 5.0 -> DB

Now I have 2 ways to do it

  1. Do it at Generic Repository (but here I will have to search the whole object graph for string properties and change the value)
  2. Do it at the time of Deserialization in WCF pipeline (but here I might have to put my custom serializer, which I don't want to do as all I want is an event during serialization where I can query the property type and change it's value)

I am in favor of approach 2 but looking for easiest way to do this, without changing the whole serializer. Is there a way it can be changed without using custom serializer. We are using XmlSerializer at present.

Looking for following input(2)

  1. Which approach would be better in performance
  2. How I can attach my little method in existing serialization process in WCF pipeline.

Thanks, Avi


Solution

  • Your code should work on the Data Layer and not the Serialization layer, given that that is where the requirement originated.

    As for implementation, you have two options.

    You can either use DbChangeTracker or you can use IDbCommandInterceptor (new in EF6) to change the behavior of your EF context.

    Below is how you can EASILY do this with change tracker

    public class FooContext : DbContext
    {
        public override int SaveChanges()
        {
            var items = ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();
            foreach(var item in items)
            foreach(var property in item.PropertyNames)
            {
                var propValue = item[property] as string;
                if(propValue != null)
                {
                    item[property] = propValue.Trim();
                }
            }
            return base.SaveChanges();
        }
    }