1

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!

EDIT: I also want control whether or not my data type can accept NULL. So, I want to change all my data types (e.g., int, nvarchar, DateTime) to not accept NULL.

2 Answers 2

2

You could make use of DataAnnotations in general, in order to specify things like this. Specifically, in the case you mentioned you need to make use of the attribute called MaxLength:

[MaxLength(40)]
public string CountryName { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.