简体   繁体   English

实体框架代码优先-确定数据类型

[英]Entity Framework Code First - determining data type

I'm learning Entity Framework using the code first approach. 我正在学习使用代码优先方法的Entity Framework Take the example below, say I have a class Employee : 以下面的示例为例,说我有一个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 . 它会自动创建一个使用表NVARCHAR(MAX)string ,并intint

How do I control the data type and data size created in the database? 如何控制在数据库中创建的data typedata size (For example, I want to use CHAR(20) instead of just NVARCHAR(MAX)?) (例如,我想使用CHAR(20)而不是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. 您可以使用“代码优先”数据注释,也可以使用流利的api。 Which I definitely prefer. 我绝对喜欢。

For the fluent api, take a look here . 对于流利的api,请看这里 Or here for a more simple and working stackoverflow example ;-). 或者在这里获得一个更简单,更有效的stackoverflow示例;-)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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