56

I have this setting in my model:

[StringLength(250)]
public string Comment { get; set; }

to set the maximum length to 250 in the database which is great.

However it's set as nvarchar(250) when the database person was expecting varchar(250).

Can somebody please tell me how to set it as a varchar from the model as opposed to an nvarchar?

AnonyMouse
  • 18,108
  • 26
  • 79
  • 131

3 Answers3

127

Use ColumnAttribute to give the datatype

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

Or use fluent API

modelBuilder.Entity<MyEntity>()
  .Property(e => e.Comment).HasColumnType("VARCHAR").HasMaxLength(250);
Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
Eranga
  • 32,181
  • 5
  • 97
  • 96
  • 1
    Thanks! I was afraid I was going to have to use `EntityFunctions.AsNonUnicode` everywhere – norepro Apr 03 '13 at 20:37
  • Edited answer to reflect that the name argument to ColumnAttribute isn't required - you can pass just the named TypeName argument if you like. Also discussed here: http://stackoverflow.com/q/5109170/176877 – Chris Moschini Apr 10 '13 at 07:46
  • 2
    I wasted one whole day setting my column details as [Column("ToDoItem", TypeName = "NVARCHAR(250)")] resulting in mysterious EF errors (courtesy EF team). Now I realized string length is a separate attribute altogether. You saved my one more day of frustration atleast. Thanks. – RBT May 09 '16 at 00:03
  • More interestingly [Column("ToDoItem", TypeName = "NVARCHAR(MAX)")] works. For MAX nvarchar length you don't need to mention the stringLength attribute separately. I'm on EF 6 btw. – RBT May 09 '16 at 00:29
  • OK using .net core 2 you'll find the model builder given above makes a varchar of only 1 character. however if you drop the HasColumnType it works correctly. This was targeting Sql Server – andrew pate May 14 '19 at 17:20
21

For some reason this older post keeps coming up in my search... so just FYI, using EF6 Core it's combined. The above answer errors out for me.

[Column(TypeName = "VARCHAR(250)")]
public string Comment {get;set;}
amd3
  • 696
  • 1
  • 6
  • 15
  • 1
    StringLength may also cause problems when a Controller PUT/POST handler attempts to marshal an enum type that's persisted as a string in the db. Using Column mitigates the issue. – bvj Jan 04 '22 at 01:04
0

Visual Studio 2022 using Net 6 and EF Core 6, database first using the -DataAnnotations parameter creates the following attributes

 /* Nullable column */
 [StringLength(250)]
 [Unicode(false)]
 public string? Comment { get; set; }

 /* Non-Nullable column */
 [StringLength(250)]
 [Unicode(false)]
 public string Comment { get; set; } = null!;
Moses
  • 78
  • 6