通过实体框架

时间:2018-08-21 12:57:12

标签: c# mysql entity-framework

我正在尝试使用Entity Framework 6将一些带有特殊字符的字符串insert放入数据库,但似乎EF在放入数据库时​​会对其进行更改。例如,“zażółćgęśląjaźń”变成“zazólcgesla jazn”。

我想保持数据不变,而将列保持为varchar。

创建数据库后,我尝试了一些注释并执行了更改排序规则和字符集的命令,但是这些尝试均失败了。

using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using MySql.Data.EntityFrameworkCore.DataAnnotations;

class Program
{
    static void Main(string[] args)
    {
        using (var context = new TestDBContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();
            // tried this
            context.Database.ExecuteSqlCommand(
                "ALTER DATABASE `TestDB` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci");
            context.insertData();
            // result: "lódz" - doesn't work either
            context.Database.ExecuteSqlCommand(
                "INSERT INTO `testtable` (`Id`, `SpecialCharacters`) VALUES (NULL, 'łódź')");
        }
    }
}

class TestDBContext : DbContext
{
    public Microsoft.EntityFrameworkCore.DbSet<TestTable> TestTable { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseMySQL("server=localhost;database=TestDB;user=root;password=;SslMode=None;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<TestTable>()
            .HasKey(t => t.Id);
    }

    // result: "zazólc gesla jazn" instead of "zażółć gęślą jaźń"
    public void insertData()
    {
        using (var context = new TestDBContext())
        {
            context.TestTable.Add(new TestTable
                {
                    SpecialCharacters = "zażółć gęślą jaźń",
                }
            );
            context.SaveChanges();
        }
    }
}

class TestTable
{
    public int Id { get; set; }

    [Column(TypeName = "varchar(17)")]
    [MySqlCharset("utf8")] // tried this
    [MySqlCollation("utf8_unicode_ci")] // tried this
    public string SpecialCharacters { get; set; }
}

(注意context.Database.ExecuteSqlCommand("INSERT INTO...也违反了数据。通过控制台(不带EF)添加此类数据就可以了。)

最后,我的问题是:如何使用Entity Framework将具有特殊字符的字符串插入DB的varchar列中?

0 个答案:

没有答案