简体   繁体   中英

.Net Core2.2 : how to change characterset in EF codefirst approach

I have tried using Charset=utf8; in the connection string and using [MySqlCharset("utf8")] in my model(which was not recognized by VsCode). I have also read about this method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<ComplexKey>(e =>
    {
      e.HasKey(p => new { p.Key1, p.Key2 });
      e.ForMySQLHasCollation("utf8"); // defining collation at Entity level
      e.Property(p => p.Key1).ForMySQLHasCharset("utf8"); // defining charset in a property
      e.Property(p => p.CollationColumnFA).ForMySQLHasCollation("utf8"); // defining collation in a property
    });
  }

but I have not tested it because I think it is tedious to do that for every single table and there should be an easier way.

Just insert the charset inside your connection string to MySql ( in your database context class ), and then you will not need to declare the charset on any property.

Example:



public  class YourDbContext : DbContext {
        private readonly IConfiguration _config;

        // See the charset in the end of this string.
        private string _yourConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword; CharSet=utf8;";

        protected override void OnConfiguring(DbContextOptionsBuilder builder) {
            builder.UseMySQL( _yourConnectionString  );
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM