How do I set a column in SQL Server to varchar(max) using ASP.net EF Codefirst Data Annotations?

c# ef-code-first entity-framework sql-server

Question

I've been searching around the web trying to figure out the right syntax to have Entity Framework Code First create my table with a column: varchar(max).

This is what I have. By default this creates varchar(128). How do I create varchar(max)?

I have tried [MaxLength] without success.

Any help would be appreciated. Thanks!

[Column(TypeName = "varchar")]
public string MediaDesc { get; set; }
1
48
6/28/2012 6:17:10 AM

Accepted Answer

[Column(TypeName = "varchar(MAX)")]

Surprisingly the most obvious solution works.

The [MaxLength] attribute only creates a varchar column with a max length that isn't MAX but - in my case (SQL Server Express 2008 R2) - 8000.

75
6/28/2012 8:21:53 AM

Popular Answer

This will get you nvarchar(max):

[StringLength(int.MaxValue)]

I don't think there's an attribute to force non-unicode (are you sure you want that?), so for varchar(max) you need a tweak in the DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Entity>().Property(x => x.MediaDesc).IsUnicode(false);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow