.NET CORE2.2:如何在EF CodeFirst方法中更改字符集



我尝试在连接字符串中使用Charset=utf8;,并在我的模型中使用[MySqlCharset("utf8")](VSCODE未识别)。我还读过有关此方法的信息:

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
    });
  }

,但我没有测试过它,因为我认为每张桌子都这样做是很乏味的,并且应该有一个更简单的方法。

只需在连接字符串中插入charset到mySQL(在数据库上下文类中),然后您无需在任何属性上声明charset。

示例:


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  );
        }
}

最新更新