Disable conversion between VARCHAR and NVARCHAR when using Entity Framework over an existing SQL server database

.net entity-framework entity-framework-6 sql sql-server

Question

I have an existing database SQL server and I'm using EF6 over it. Let's assume I have the following code:

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

Usage:

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

What can possibly go wrong? Well, if the Bar column has type VARCHAR(MAX) instead of NVARCHAR(MAX), then we are in a bad position, because VARCHAR cannot properly store that string of Unicode characters, so we get a bunch of question marks instead.

So, the question is: can I some how disable this conversion between VARCHAR and NVARCHAR and enforce EF to throw some sort of type mismatch exception during SaveChanges? I've tried to use this in my configuration class:

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

but it did nothing.

Thanks in advance.

1
2
3/17/2018 10:39:16 AM

Popular Answer

The default data type for string columns is nvarchar(MAX), you don't have the need to set data type in your columns for changing to NVARCHAR(MAX). Ef has default conventions that Specify it. here is explained for knowing conventions.

if you want config generally convention for your models, you can do this:

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

on your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Add(new DataTypeConvention());
}
0
3/17/2018 8:46:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow