Jason Bak Jason Bak - 5 months ago 24
SQL Question

Way to have control over what data type I pass into my tables using C# Entity Framework

I'm using code-first entity framework to create tables in a SQL database from objects. I'd like to have control over what types my variables are once they are in the SQL table.

For example, I have a table with a CountryName column. Currently, it has the data type nvarchar(MAX). I'd like for the data type to be nvarchar(40) to save memory.

I can do this manually in SSMS, but it'll take me a few hours to do this for all my tables. I'm looking for a way to do this in code.

Thanks in advance!

Answer Source

You can use DataAnnotations to configure your model. To set the length to 40 you would apply the attribute MaxLength to a property.

[MaxLength(40)]

Or, as your question asks to do this in code you override the OnModelCreating in your DbContext and use the Fluent API to configure your model.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Configure domain classes using modelBuilder here

    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Student>()
                .Property(p => p.CountryName)
                .HasMaxLength(40);
}

Walk through all the pages in the following tutorial to learn all the different ways to configure properties in your mode.http://www.entityframeworktutorial.net/code-first/fluent-api-in-code-first.aspx