简体   繁体   中英

Entity Framework Code First - determining data type

I'm learning Entity Framework using the code first approach. Take the example below, say I have a class Employee :

public class employee
{
    public int id{ get; set; }
    public string fName { get; set; }
    public string lName { get; set; }
    public string email { get; set; }
}

It will automatically create the table using NVARCHAR(MAX) for string , and int for int .

How do I control the data type and data size created in the database? (For example, I want to use CHAR(20) instead of just NVARCHAR(MAX)?)

Try the following:

    public class TestContext : DbContext
    {
        public DbSet<employee> Employees { get; set; }

        protected override void OnModelCreating(DbModelBuilder mb)
        {
            mb.Entity<employee>()
                .Property(i => i.fName)
                .HasColumnType("char")
                .HasMaxLength(20);

            base.OnModelCreating(mb);
        }
    }

You can either use Code First Data Annotations, or use the fluent api. Which I definitely prefer.

For the fluent api, take a look here . Or here for a more simple and working stackoverflow example ;-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM