Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.3.1 - code first automatic migrations - how to specify column width

I am trying to find examples or documentation related to DbMigration and ColumnModel. I simply want to specify width of string propery in DBMigration Up method E.g.

AddColumn("Districts", "Code", c => c.String());

will create nvarchar(max) - and I want to specify maxlength(20) for example. Is this integrated with EntityTypeConfiguration or I have to add also manually

this.Property(t => t.Name).HasColumnName("Code").IsRequired().HasMaxLength(20);

MSDN help doesn't give any examples and walkthrough on ef4 blog covers only basics

like image 443
Ivo Stoyanoff Avatar asked Nov 26 '25 10:11

Ivo Stoyanoff


2 Answers

If you use AddColumn directly you can simply use:

AddColumn("Districts", "Code", c => c.String(maxLength: 20));

If you define max length in EntityTypeConfiguration (which is correct approach) EF Migration will handle it for you.

like image 71
Ladislav Mrnka Avatar answered Nov 29 '25 20:11

Ladislav Mrnka


The configuration of the columns should be done as data annotations. To make a string column have a specific width, use the StringLengthAttribute:

[Required] // Makes column not null
[StringLength(20)] // Makes it a nvarchar(20) instead of nvarchar(max)
public string SomeString {get;set;}
like image 42
Anders Abel Avatar answered Nov 29 '25 20:11

Anders Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!