12

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.

Laurence Frost
  • 2,759
  • 3
  • 28
  • 45

3 Answers3

10

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"));
    }
  • 1
    Use this if you want to set them all to varchar without checking for attributes: `modelBuilder.Properties().Configure(c => c.HasColumnType("varchar"));` – Jamie Ide May 13 '15 at 17:48
5

Or

modelBuilder.Properties<string>().Configure(c => c.IsUnicode(false));
Floern
  • 33,559
  • 24
  • 104
  • 119
Elugui
  • 71
  • 1
  • 1
4

You must write it as:

[Column(TypeName = "VARCHAR")]
public string firstName { get; set; }

For many info please look at this link

Community
  • 1
  • 1
Elvin Mammadov
  • 25,329
  • 11
  • 40
  • 82
  • I realise it can be written like this as per my example. I'm sure it must be possible to do it globally though. – Laurence Frost Aug 18 '13 at 00:17
  • Did you try fluent api for this?, because sometimes DataAnnotation doesn't give us best result – Elvin Mammadov Aug 18 '13 at 03:01
  • I had this problem too, and this worked for me. If you already created NVarchar columns like I did, this will make the next Code First migration you add fix the problem (convert the NVarchar columns over to Varchar). Bravo! – Greg Barth Feb 02 '15 at 17:24