Entity Framework Core – Improved Value Conversion Support

Entity Framework Core (EF) 2.1 introduced a new feature called Value Conversion. Now, we are able to map custom .NET types to a type the database understands and vice versa. This long-awaited feature is especially popular among software engineers following the domain driven design (DDD) patterns.

In diesem Artikel:

pg
Pawel Gerr ist Architekt und Consultant bei Thinktecture. Er hat sich auf .NET Core Backends spezialisiert und kennt Entity Framework von vorne bis hinten.

At the moment the value conversion has some limitations that will be removed in the future. The limitation I want to address in this post is the fallback to client-side evaluation in some fairly simple but rather frequently needed use case.

As an example I will use an entity containing the property of type System.Drawing.Color:

				
					public class Product
{
   ...
   public Color Color { get; set; }
}
				
			

And the corresponding value conversion:

				
					modelBuilder.Entity<Product>()
            .Property(p => p.Color)
            .HasConversion(color => color.Name, name => Color.FromName(name));

				
			

With provided conversion, only the name of the color is saved and when the name comes back from the database then it is mapped to an instance of Color.

Having the converter we are now able to insert, update and select the property Color.

				
					DemoDbContext ctx = ...;

// adding new product
ctx.Products.Add(new Product { ..., Color = Color.Green});
ctx.SaveChanges();

// retrieving all products
var products = await ctx.Products.ToListAsync();
				
			

In both cases we get the expected results. Now let us fetch all products with the color Green.

				
					var products = await ctx.Products
                        .Where(p => p.Color == Color.Green)
                        .ToListAsync();
				
			

This time the result is correct as well but EF emits a warning: _The LINQ expression where ([p].Color == __Green_0) could not be translated and will be evaluated locally._

A look at the SQL statement proves that the filtering is done in memory and not in the database:

				
					SELECT ..., [p].[Color]
FROM [Products] AS [p]

				
			

When having just a few products in the database then there is nothing to worry about but with a lot of records this query may lead to major performance issues.

Implement the "IRelationalTypeMappingSourcePlugin"

The provided value converter is applied to the property Color only so the constant value on the right side of the equation is not being converted. What we need is kind of global value converter, so let’s build one.

To provide EF with the value converter for Color we have to implement the interface IRelationalTypeMappingSourcePlugin that has just 1 method FindMapping. First, we prepare the mapping that will be returned by the plugin. The type mapping is derived from RelationalTypeMapping and is providing the CLR type and the converter to the base class.

Actually, the store type nvarchar(50) is not being used in this case so you can even write rumpelstilzchen if you want to.

				
					public class ColorTypeMapping : RelationalTypeMapping
{
   private static readonly ValueConverter<Color, string> _converter
      = new ValueConverter<Color, string>(color => color.Name,
                                          name => Color.FromName(name));

   public ColorTypeMapping()
      : base(new RelationalTypeMappingParameters(
                   new CoreTypeMappingParameters(typeof(Color), _converter),
                   "nvarchar(50)"))
   {
   }
}
				
			

The plugin itself is just waiting for the method to be called with the CLR type Color to return previously implemented ColorTypeMapping.

				
					public class ColorTypeMappingPlugin : IRelationalTypeMappingSourcePlugin
{
   public RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo)
   {
      if (mappingInfo.ClrType == typeof(Color))
         return new ColorTypeMapping();

      return null;
   }
}
				
			

Register the plugin with dependency injection

Now, we have to register the ColorTypeMappingPlugin with the (internal) dependency injection (DI) of EF. For that we have to implement IDbContextOptionsExtension like I did in one of my previous blogs (EF Core: Custom Functions – search for the first occurrence of IDbContextOptionsExtension) or use the nuget package Thinktecture.EntityFrameworkCore.Relational (docs).

By using the nuget package the registration of the plugin looks as following:

				
					services
   .AddDbContext<DemoDbContext>(builder => builder
                        ...
                        .AddRelationalTypeMappingSourcePlugin<ColorTypeMappingPlugin>()
				
			

Trying out the plugin

Let’s look at the SQL statements when we query for products with the color Green:

				
					// having the value `Color.Green` inline we get the SQL
//    SELECT ..., [p].[Color]
//    FROM [Products] AS [p]
//    WHERE [p].[Color] = @__Green_0

var products = await ctx.Products
                        .Where(p => p.Color == Color.Green)
                        .ToListAsync();

// but more often the filter comes via parameter
//    SELECT ..., [p].[Color]
//    FROM [Products] AS [p]
//    WHERE [p].[Color] = @__color_0

var color = Color.Green;
var products = await ctx.Products
                        .Where(p => p.Color == color)
                        .ToListAsync();
				
			

With less than 20 lines of code we were able to improve the usability of the value conversion so the EF model can be as close as possible to our domain model without loosing performance. It is just a matter of time until EF team removes the limitation for this rather simple use cases. Still, there will be some edge cases in the future that will require some tweaking once again.

Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Newsletter Anmeldung
Diese Artikel könnten Sie interessieren
.NET
pg

Advanced Value Object Patterns in .NET

While basic value objects solve primitive obsession, complex domain requirements need sophisticated modeling techniques. This article explores advanced patterns using Thinktecture.Runtime.Extensions to tackle real-world scenarios: open-ended dates for employment contracts, composite file identifiers across storage systems, recurring anniversaries without year components, and geographical jurisdictions using discriminated unions.
19.10.2025
.NET
pg

Discriminated Unions in .NET: Modeling States and Variants

Domain models often involve concepts that exist in multiple distinct states or variations. Traditional approaches using enums and nullable properties can lead to invalid states and scattered logic. This article explores how discriminated unions provide a structured, type-safe way to model domain variants in .NET, aligning perfectly with Domain-Driven Design principles while enforcing invariants at the type level.
06.10.2025
.NET
pg

Smart Enums in .NET: Integration with Frameworks and Libraries

Learn how to seamlessly integrate Smart Enums with essential .NET frameworks and libraries. This article covers practical solutions for JSON serialization, ASP.NET Core model binding for both Minimal APIs and MVC controllers, and Entity Framework Core persistence using value converters. Discover how Thinktecture.Runtime.Extensions provides dedicated packages to eliminate integration friction and maintain type safety across your application stack.
21.09.2025
.NET
pg

Value Objects in .NET: Enhancing Business Semantics

Value objects are fundamental building blocks in Domain-Driven Design, serving far more than simple data wrappers. This article explores their strategic importance in bridging technical code and business concepts, enforcing domain rules, and fostering clearer communication with domain experts. Learn how to build robust aggregates, cultivate ubiquitous language, and encapsulate domain-specific behavior using Thinktecture.Runtime.Extensions in .NET applications.
16.09.2025
.NET
pg

Pattern Matching with Discriminated Unions in .NET

Traditional C# pattern matching with switch statements and if/else chains is error-prone and doesn't guarantee exhaustive handling of all cases. When you add new types or states, it's easy to miss updating conditional logic, leading to runtime bugs. The library Thinktecture.Runtime.Extensions solves this with built-in Switch and Map methods for discriminated unions that enforce compile-time exhaustiveness checking.
26.08.2025
.NET
pg

Value Objects in .NET: Integration with Frameworks and Libraries

Value Objects in .NET provide a structured way to improve consistency and maintainability in domain modeling. This article examines their integration with popular frameworks and libraries, highlighting best practices for seamless implementation. From working with Entity Framework to leveraging their advantages in ASP.NET, we explore how Value Objects can be effectively incorporated into various architectures. By understanding their role in framework integration, developers can optimize data handling and enhance code clarity without unnecessary complexity.
12.08.2025