Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 951
Laurence Frost Avatar asked Aug 16 '13 10:08

Laurence Frost


3 Answers

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"));
    }
like image 61
Rafael Berrocal Justiniano Avatar answered Oct 10 '22 17:10

Rafael Berrocal Justiniano


You must write it as:

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

For many info please look at this link

like image 28
Elvin Mammadov Avatar answered Oct 10 '22 16:10

Elvin Mammadov


Or

modelBuilder.Properties<string>().Configure(c => c.IsUnicode(false));
like image 28
Elugui Avatar answered Oct 10 '22 15:10

Elugui