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.