

Built-in convertersĪs mentioned above, EF Core ships with a set of pre-defined ValueConverter classes, found in the namespace.

This can be useful when multiple properties use the same conversion. V => (EquineBeast)Enum.Parse(typeof(EquineBeast), v))

For example: protected override void OnModelCreating(ModelBuilder modelBuilder) The ValueConverter can instead be created explicitly. The ValueConverter classĬalling HasConversion as shown above will create a ValueConverter instance and set it on the property. Then the enum values will be saved as strings in the database without any further configuration in OnModelCreating. For example, if the entity type is defined like so: The same thing can be achieved by explicitly specifying the database column type. Instead, EF Core will pick the conversion to use based on the property type in the model and the requested database provider type.įor example, enum to string conversions are used as an example above, but EF Core will actually do this automatically when the provider type is configured as string using the generic type of HasConversion: protected override void OnModelCreating(ModelBuilder modelBuilder) Then, override ConfigureConventions in your context type and configure the converter as follows: protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)ĮF Core contains many pre-defined conversions that avoid the need to write conversion functions manually. To do this, define your value converter as a class: public class Currenc圜onverter : ValueConverter Rather than doing this manually for each property, you can use pre-convention model configuration to do this once for your entire model. It's common for the same value converter to be configured for every property that uses the relevant CLR type. See GitHub issue #13850 for more information. This makes the implementation of conversions easier and allows them to be shared amongst nullable and non-nullable properties. A null in a database column is always a null in the entity instance, and vice-versa. A null value will never be passed to a value converter.
