Question

I was wondering how to change input values when using the Entity Framework. Till now I'm using selfmade custom classes which I transform to entity classes. I think I'm doubling the work i have to do. In the custom class I transform the incomming value at the setter. Postal codes in the netherlands are 4 digits plus 2 characters. Some people seperate them with a space, others join them together. At this moment a Regex wil seperate the digits from the characters if necessary. When using the Entity Framework. Is there a possibility to change the incomming value before writing the value to te database? And if so how do I do so?

I was searching for validation but all examples I saw where only throwing errors without effectively transforming the value.

Example of Dutch Postal Code: "5126HG" or "5126 HG" should both result in the same result in the database. I already know how to change, but not where and how to apply.

Était-ce utile?

La solution

I think that using custom classes is a good idea, it's similat to implement the DTO pattern and it's a good method to separate business layer from data access layer. But if you want to add some validation / modification methods to the entity classes you can do it.

If you are using EF 4.1 you have POCO classes for entities createted by the generator as partial classes. You can add your custom partial classes adding validation methods, but you need to explicitly call these methods before executing a db operation.

Another way is using a custom SaveChange handler. Here you can find an example of SaveChange customization. http://msdn.microsoft.com/en-us/library/cc716714.aspx

Autres conseils

Is there a possibility to change the incomming value before writing the value to te database? And if so how do I do so?

It is better to have some separate Controller class with a method that takes, validates, transforms inputs and only then sets Entity properties with valid, correct and consistent values.

This way your Entities are always valid and correct and you never ever need a nonstandard mechanism to change values before writing to the database.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top