简体   繁体   中英

Trim Strings On Entity Framework Save

I'm using Entity Framework Code First within an ASP.NET MVC web application where the customers have a bad habit to add white space at the end of strings.

Obviously Trim() is the correct answer to fix the problem, but remembering to trim everything throughout the project isn't the right thing to do. Did some digging around and found ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder? where they created a custom model binder, but I'm worried there will be a performance hit on each page load of the application when the model is binded. Seems like trimming as SaveChanges() is called would be the most performant way to do it since things would be stored trimmed into the database.

So my question, is overriding SaveChanges() and getting all the added and modified objects from the ObjectContext then using reflection to trim every string the right thing to do here? Or is the model binder the correct way to go?

I think you are worrying about performance too much. The model binder is fine we do that exact thing over our entire application.

MVC Framework is pretty big, an extra model binder isn't a lot of overhead.

Also we found cases where we had to prevent trim. Therefore model binder was perfect as it allowed us to exclude certain fields.

Model binder is standard MVC behavior. If you do it at the DB level its hidden.

So if it was me I would do it in the ModelBinder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM