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);
}
}
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.