在现有SQL Server数据库上使用Entity Framework时,禁用VARCHAR和NVARCHAR之间的转换

问题描述 投票:2回答:1

我有一个现有的数据库SQL服务器,我正在使用EF6。我们假设我有以下代码:

private sealed class Foo
{
    public int Id { get; set; }

    public string Bar { get; set; }
}

private sealed class FooConfiguration : EntityTypeConfiguration<Foo>
{
    public FooConfiguration()
    {
        ToTable("Foos");
        HasKey(e => e.Id);
        Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

private class FooContext : DbContext
{
    public FooContext(string connectionString)
        : base(connectionString)
    {
        Database.SetInitializer<FooContext>(null);
    }

    public virtual DbSet<Foo> Foos { get; set; }

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

        modelBuilder.Configurations.Add(new FooConfiguration());
    }
}

用法:

const string bar = "حالياً البحث عبر جوجل";
int fooId;
using (var db = new FooContext(connectionString))
{
    var foo = db.Foos.Add(new Foo { Bar = bar });
    db.SaveChanges();
    fooId = foo.Id;
}

using (var db = new FooContext(connectionString))
{
    var foo = db.Foos.First(f => f.Id == fooId);
    if (foo.Bar != bar)
    {
        Console.WriteLine("Oops!");
    }
}

什么可能出错?好吧,如果Bar列有类型VARCHAR(MAX)而不是NVARCHAR(MAX),那么我们处于不利位置,因为VARCHAR无法正确存储Unicode字符串,所以我们得到了一堆问号。

所以,问题是:我能否在VARCHARNVARCHAR之间禁用这种转换并强制EF在SaveChanges期间抛出某种类型的不匹配异常?我试过在我的配置类中使用它:

Property(e => e.Bar).IsUnicode(true);
Property(e => e.Bar).HasColumnType("NVARCHAR(MAX)");

但它没有做任何事情。

提前致谢。

sql .net sql-server entity-framework entity-framework-6
1个回答
0
投票

string列的默认数据类型是nvarchar(MAX),您无需在列中设置数据类型以更改为NVARCHAR(MAX)。 Ef具有指定它的默认约定。 here解释为了解惯例。

如果你想为模型配置一般约定,你可以这样做:

public class DataTypeConvention : Convention
{
    public DataTypeConvention()
    {
        Properties<string>().Configure(config => { config.HasColumnType("nvarchar(MAX)"); });
    }
}

在你的DbContext上:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Add(new DataTypeConvention());
}
© www.soinside.com 2019 - 2024. All rights reserved.