Configure every column manually to a specific CharSet and Collation,
In case you cannot change server/schema default CharSet or Collation (you are not the Server administrator)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Pomelo.EntityFrameworkCore.MySql.Extensions;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
namespace Data
{
public static class Extensions
{
internal static PropertyBuilder<string> TextField(this PropertyBuilder<string> string_column, int max_length)
{
string_column.TextField(CharSet.Utf8Mb4, "utf8mb4_unicode_ci", max_length);
return string_column;
}
internal static PropertyBuilder<string> TextField(this PropertyBuilder<string> string_column, CharSet char_set, string collation, int max_length)
{
string_column.HasColumnType($"VARCHAR({max_length}) CHARACTER SET {char_set} COLLATE {collation}");
return string_column;
}
}
}
Set character set of each property
protected override void OnModelCreating(ModelBuilder builder)
{
...
builder.Entity<TABLE>().Property(t => t.Name).TextField(1024);
...
}
Check the result by query column collation settings
> mysql.exe --login-path=mysql1 --database=test1 -e "select column_name, character_set_name, collation_name from information_schema.columns where table_name = 'TABLE';"
+-------------+--------------------+--------------------+
| column_name | character_set_name | collation_name |
+-------------+--------------------+--------------------+
| Id | NULL | NULL |
| Name | utf8mb4 | utf8mb4_unicode_ci |
| CreatedTime | NULL | NULL |
| UpdatedTime | NULL | NULL |
+-------------+--------------------+--------------------+
My Entity Framework Project lib with MySQL 5.7.21
.
<ItemGroup>
...
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="5.0.0-alpha.2" />
</ItemGroup>
Noted the following can set CharSet
but Collation
is fixed to utf8mb4_general_ci
.
services.AddPooledDbContextFactory<ApplicationDbContext>(
options => options
.UseMySql(
Configuration["ConnectionString"],
new MySqlServerVersion(new Version(5, 7, 21)),
mySqlOptions =>
{
mySqlOptions
.CharSetBehavior(CharSetBehavior.AppendToAllColumns);
mySqlOptions.CharSet(CharSet.Utf8Mb4);
})
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
);