将特殊字符分配给字符串时,剃刀页面弄乱了编码

时间:2019-07-09 14:49:11

标签: c# mysql razor entity-framework-core special-characters

更新4:

哦,哇,显然不是EF或配置问题。

Somehow the .razor page variable assigment is messing up the data.

现在不确定如何继续该问题,但是我至少编辑了标题以反映当前问题,即:在为字符串分配特殊字符时,剃刀页面弄乱了编码。


问题:

无论我做什么,我插入MySQL 5.7.17数据库的字符始终显示为�:

Database lookup

尽管有类似的帖子,但没有一种解决方案对我有用,我已经用尽了我的研究能力。

我尝试过的事情:

代码:

连接字符串:

"MySQL": "server=localhost;user=root;database=sgn;charset=utf8mb4;"

UserModel.cs

namespace source.Data.Models
{
    [MySqlCharset("utf8mb4")]
    [MySqlCollation("utf8mb4_unicode_ci")]
    public class UserModel
    {
        public UserModel() { }

        [Key]
        public long Id { get; set; }
        [MySqlCharset("utf8mb4")]
        [MySqlCollation("utf8mb4_unicode_ci")]
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Language { get; set; }
        public string StartPage { get; set; }
    }
}

DatabaseContext.cs

namespace source.Data.Database
{
    public class DatabaseContext : DbContext
    {
        private IConfiguration Configuration;
        public DbSet<UserModel> Users { get; set; }

        public DatabaseContext(DbContextOptions<DatabaseContext> options, IConfiguration configuration)
            : base(options)
        {
            Configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseMySQL(Configuration.GetSection("AppSettings").GetSection("Database").GetSection("ConnectionString")["MySQL"]);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserModel>().Property(p => p.Username).IsUnicode(true);
            base.OnModelCreating(modelBuilder);
        }

    }
}

DesignTimeDatabaseContextFactory.cs

namespace source.Data.Database
{
    public class DesignTimeDatabaseContextFactory : IDesignTimeDbContextFactory<DatabaseContext>
    {
        private IConfiguration Configuration;
        private AppSettingsService AppSettings;

        public DesignTimeDatabaseContextFactory()
        {
        }

        public DesignTimeDatabaseContextFactory(IConfiguration configuration, AppSettingsService appSettings)
        {
            Configuration = configuration;
            AppSettings = appSettings;
        }

        public DatabaseContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<DatabaseContext>();

            builder.UseMySQL(AppSettings.ConnectionString);


            return new DatabaseContext(builder.Options, Configuration);
        }
    }
}

Create.razor-这是将用户添加到数据库的地方。请注意,该项目使用Blazor,因此请不要与“ @functions”标签混淆。这两个函数均未正确添加数据,并且注释的是我尝试过的准备好的语句。

<div class="login_form">
    <h3>Create Account</h3>

    <button @onclick="@(e => AddEntry())">Add DB User!</button><br />
    <button @onclick="@(e => AddEntry2())">Add TEST!</button><br />
</div>

@functions {

    void AddEntry2()
    {
        UserModel test = new UserModel();

        test.Username = "Test çã";
        test.FirstName = "Michel";
        test.LastName = "Arendt";
        test.Email = "mail@gmail.com";
        test.Password = "123";
        test.Language = "pt-BR";
        test.StartPage = "/Home/";

        db.Database.ExecuteSqlCommand("SET NAMES utf8mb4");
        db.Database.ExecuteSqlCommand("SET character_set_connection = utf8mb4");
        db.Database.ExecuteSqlCommand("INSERT INTO Users (Username) VALUES (N'" + test.Username + "')");
        db.SaveChanges();


        //using (SqlConnection connection = new SqlConnection(AppSettings.DatabaseConnectionString()))
        //{
        //    connection.Open();
        //    SqlCommand command = new SqlCommand(null, connection);

        //    // Create and prepare an SQL statement.
        //    command.CommandText =
        //        "INSERT INTO Users (Username) " +
        //        "VALUES (@username)";
        //    SqlParameter username = new SqlParameter("@username", SqlDbType.NVarChar, 100);
        //    username.Value = "Garçon";
        //    command.Parameters.Add(username);

        //    // Call Prepare after setting the Commandtext and Parameters.
        //    command.Prepare();
        //    command.ExecuteNonQuery();
        //}
    }

    void AddEntry()
    {
        UserModel waitress = new UserModel();

        waitress.Username = "Garçon";
        waitress.FirstName = "Test";
        waitress.LastName = "Test";
        waitress.Email = "mail@gmail.com";
        waitress.Password = "123";
        waitress.Language = "pt-BR";
        waitress.StartPage = "/Home/";

        db.Users.Add(waitress);
        db.SaveChanges();
    }
}

source.csproj(依赖关系参考)

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>7.3</LangVersion>
    <RestorePackages>false</RestorePackages>
    <Version>0.10.0</Version>
    <Authors>Michel Arendt</Authors>
    <Product>SGN</Product>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>
  <ItemGroup>
    <Content Remove="compilerconfig.json" />
  </ItemGroup>
  <ItemGroup>
    <None Include="compilerconfig.json" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="ElectronNET.API" Version="5.22.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0-preview6.19304.6" />
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.16" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="electron.manifest.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
</Project>

数据库配置

数据库和列的默认排序规则和字符集分别是utf8mb4_unicode_ci和utf8mb4:

Default database character set and collation

Columns character set and collation


关于为解决该问题或我正在犯的错误还有哪些尝试?

谢谢!


更新:

按照Bradley Grainger的建议(在评论中),我切换到了 Pomelo.EntityFrameworkCore.MySql ,但这无助于解决该问题。我更改过的文件现在是:

将构建从 Startup.cs DesignTimeDatabaseContextFactory.cs 更改为使用:

builder
                .UseMySql(AppSettings.ConnectionString,
                    mysqlOptions =>
                    {
                        mysqlOptions
                            .CharSetBehavior(CharSetBehavior.AppendToAllColumns)
                            .AnsiCharSet(CharSet.Utf8mb4)
                            .UnicodeCharSet(CharSet.Utf8mb4);
                    });

创建剃刀

void AddEntry2()
{
    UserModel test = new UserModel();

    test.Username = "Test çã";
    test.FirstName = "Michel";
    test.LastName = "Arendt";
    test.Email = "mail@gmail.com";
    test.Password = "123";
    test.Language = "pt-BR";
    test.StartPage = "/Home/";

    using (MySqlConnection connection = new MySqlConnection(AppSettings.ConnectionString))
    {
        connection.Open();
        MySqlCommand command = new MySqlCommand(null, connection);

        // Create and prepare an SQL statement.
        command.CommandText =
            "INSERT INTO Users (Username) " +
            "VALUES (@username)";
        MySqlParameter username = new MySqlParameter("@username", MySqlDbType.LongText, 100);
        username.Value = "Garçon";
        command.Parameters.Add(username);

        // Call Prepare after setting the Commandtext and Parameters.
        command.Prepare();
        command.ExecuteNonQuery();
    }
}

认为这会有所帮助,因此我还在本地服务器上将MySQL初始化(my.ini)设置为:

[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_general_ci

但是,没有任何效果。还有其他想法吗?


更新2:

要弄清是数据库还是EF Core问题,我设置了一个简单的PHP脚本在数据库中插入相同的条目。

On this image entry 1 and 2 are inserted from EF Core while entry 3 was inserted from PHP

从图像中可以看出,由于PHP的插入工作正常,数据库似乎很好。

添加条目时如何确保EF Core使用“ utf8mb4”编码?


1 个答案:

答案 0 :(得分:1)

正如Thomas Schmidt在OP的评论中所建议的那样,这个问题是我从未想到过的其他地方,这是Visual Studio保存文件所使用的编码。该问题的解决方案描述如下:

razor view » character rendered as »

解决方案:

选择要更改其编码的文件,然后单击文件菜单,然后将“ PAGE”另存为,然后选择Save with Encoding...并选择所需的编码。


我已编辑帖子的问题标题以反映当前问题。让我知道是否应该将其改回,因为我不确定如何继续进行操作。