CodeFirst简单演示的步骤

CodeFirst简单演示的步骤

  1. 创建实体类【Student】

public class Student

    {

        public long Id { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }

        public DateTime CreateTime { get; set; }

        public short IsDelete { get; set; }

    }

  1. 创建数据库【名称为CodeFirstDB】
  2. 配置连接字符串

<!--数据库配置-->

    <add name="consrt" connectionString="server=.;database=CodeFirstDB;uid=sa;pwd=123456" providerName="System.Data.SqlClient"/>

  1. 创建数据库上下文类

public class MyDbContext : DbContext

    {

        public MyDbContext()

            : base("name=consrt")

        {

        }

        /// <summary>

        /// 创建数据库的策略

        /// </summary>

        /// <param name="modelBuilder"></param>

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            base.OnModelCreating(modelBuilder);

        }

        public DbSet<Student> Students { get; set; }

    }

  1. 实体类的配置文件【在项目中创建文件夹ModelConfig,在里面添加实体类的 配置信息【FluentAPI】】

public class StudentConfig : EntityTypeConfiguration<Student>

    {

        public StudentConfig()

        {

            this.ToTable("Students");

            this.Property(p => p.Name)

                .HasMaxLength(30)//最大长度

                .IsRequired()//不允许为空

                .IsUnicode(false);// 是 varchar

            this.Property(p => p.Address)

                .HasMaxLength(100)//最大长度

                .IsOptional()//允许为空

                .IsUnicode(true)//是 n

                .IsFixedLength();//固定长度 nchar(100)

          

        }

    }

原文地址:https://www.cnblogs.com/Learnblog/p/9993208.html