Laurence Frost
Laurence Frost

Reputation: 2993

Entity Framework 5 code first map string to varchar globally

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.

Upvotes: 12

Views: 9615

Answers (3)

Elugui
Elugui

Reputation: 71

Or

modelBuilder.Properties<string>().Configure(c => c.IsUnicode(false));

Upvotes: 5

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

Upvotes: 10

Elvin Mammadov
Elvin Mammadov

Reputation: 27397

You must write it as:

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

For many info please look at this link

Upvotes: 4

Related Questions