user10630162
user10630162

Reputation:

Entity Framework Core 7 apply custom ValueConverter to Inserts and Updates

I am struggling to understand how to apply a custom ValueConverter to all the properties of all the models before every insert and update.

According to this resource it can be done: https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations

"Value converters allow property values to be converted when reading from or **writing ** to the database"

I was able to accomplish this, but only when reading from the database, overriding ConfigureConventions in the Context:

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        configurationBuilder.Properties<string>().HaveConversion<ToUpperConverter>();
    }

Converter

    public class ToUpperConverter : ValueConverter<string, string>
    {
        public ToUpperConverter() : base(v => v, v => v.Trim().ToUpper())
        {
        }
    }

Tried also to override the method SaveChangesAsync in the Context, this works but obviously I don't want to go manually for every property and for every model considering they can change at every time. Using reflection here can be an option, but I am not really a big fan of it.

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
    foreach (var entry in ChangeTracker.Entries<Player>())
    {
        if (entry.State == EntityState.Modified || entry.State == EntityState.Added)
        {
            entry.Entity.Name = entry.Entity.Name.ToUpper();
            entry.Entity.MiddleName = entry.Entity.MiddleName?.ToUpper();
            entry.Entity.Surname = entry.Entity.Surname.ToUpper();
        }
    }
   return await base.SaveChangesAsync(cancellationToken);
}

Upvotes: 2

Views: 3274

Answers (1)

user10630162
user10630162

Reputation:

Solved, after spending on this an entire day.. The first argument of the converter is the conversion happening to the database, the second argument is the conversion happening from the database.

public class ToUpperConverter : ValueConverter<string, string>
{
    public ToUpperConverter() : base(
        // writing to the database
        v => v.Trim().ToUpper(),
       // reading from the database
       v => v.Trim().ToUpper())
    {
    }
}

Source: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.builders.propertiesconfigurationbuilder.haveconversion?view=efcore-6.0

"The type to convert to and from or a type that inherits from ValueConverter."

Upvotes: 4

Related Questions