I am playing around with EF 5 and code first. So far I really like it, but I have noticed it defaults string columns to nvarchar. If I want to use varchar, then I have to explicitly tell it to.
I can force it to use varchar instead of nvarchar for strings as follows:
public class Member
{
public int id { get; set; }
[MaxLength(255), Required, Column(TypeName = "varchar")]
public string firstName { get; set; }
[MaxLength(255), Required, Column(TypeName = "varchar")]
public string surname { get; set; }
}
I would typically use varchar instead of nvarchar in almost all cases though, so I would much prefer to have string columns globally mapped to varchar, and to be able to set nvarchar on a per-column basis as above if I need to.
Does anyone know a way to do this? I am trying to omit the need for typing [Column(TypeName = "varchar")] for every string column in my model.
on EF 6 you can use this to map every string property to use varchar instead nvarchar
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties()
.Where(x =>
x.PropertyType.FullName.Equals("System.String") &&
!x.GetCustomAttributes(false).OfType<ColumnAttribute>().Where(q => q.TypeName != null && q.TypeName.Equals("varchar", StringComparison.InvariantCultureIgnoreCase)).Any())
.Configure(c =>
c.HasColumnType("varchar"));
}
You must write it as:
[Column(TypeName = "VARCHAR")]
public string firstName { get; set; }
For many info please look at this link
Or
modelBuilder.Properties<string>().Configure(c => c.IsUnicode(false));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With