EF Code First:创建表,Migrations迁移

 

 

1.打开NuGet安装EntityFramework 

2.创建:Models(数据模型),Config(约束),Data(表数据),Context.cs(数据库连接),Initializer.cs(初始化文件)

 

3.在Models中创建表字段

namespace CodeFirst.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }

    }
}
View Code

 外键关联

using System.ComponentModel.DataAnnotations.Schema;

namespace CodeFirst.Models
{
    public class Class
    {
        public int ID { get; set; }
        public int StudentID { get; set; }

        [ForeignKey("StudentID")]
        public Student Student { get; set; }
    }
}
View Code

4.在config.cs中定义约束条件:主键(HasKey),复合唯一性约束(IndexAnnotation)

  studentConfiguration.cs

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration;
using CodeFirst.Models;

namespace CodeFirst.Config
{
    class StudentConfiguration : EntityTypeConfiguration<Student>
    {
        public StudentConfiguration()
        {
            HasKey(x => x.ID);
            // Unique constraint
            Property(x => x.Name).HasMaxLength(50).IsRequired().HasColumnAnnotation(
                IndexAnnotation.AnnotationName,
                new IndexAnnotation(new IndexAttribute("UC_ Student_Name", 1) { IsUnique = true }));
        }
    }
}
View Code

  ClassConfiguration.cs

using CodeFirst.Models;
using System.Data.Entity.ModelConfiguration;

namespace CodeFirst.Config
{
    class ClassConfiguration : EntityTypeConfiguration<Class>
    {
        public ClassConfiguration()
        {
            HasKey(t => t.ID);
            Property(x => x.Name).HasMaxLength(30).IsOptional();
        }
    }
}
View Code

5.编写Context.cs

using CodeFirst.Config;
using CodeFirst.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace CodeFirst
{
    public class CodeFirstContext : DbContext
    {
        public CodeFirstContext()
            : base("name=Context")
        {
            this.Database.CommandTimeout = 180;
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Class> Classes { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Configurations.Add(new StudentConfiguration());
            modelBuilder.Configurations.Add(new ClassConfiguration());
            //modelBuilder.Entity<Department>().MapToStoredProcedures();
        }
    }
}
View Code

6.编写Initializer.cs

using System.Data.Entity;

namespace CodeFirst
{
    public class CodeFirstInitializer : CreateDatabaseIfNotExists<CodeFirstContext>
    {
        protected override void Seed(CodeFirstContext context)
        {
            //context.Student.AddRange(StudentData.All());
            //加入初始数据,需要在程序中运行
            base.Seed(context);
        }
    }
}
View Code

 6.1数据初始化的三种机制:

   a.CreateDatabaseIfNotExists: 在没有数据库是创建一个,这是默认行为

 public class CodeFirstInitializer : CreateDatabaseIfNotExists<CodeFirstContext>
    {
        ////此处只有第一次运行才会创建新的数据库,每次的Id都一样。
        protected override void Seed(CodeFirstContext context)
        {
            base.Seed(context);
        }
    }
View Code

     b.DropCreateDatabaseAlways:每次运行时都重新生成数据库方法

public class CodeFirstInitializer : DropCreateDatabaseAlways<CodeFirstContext>
    {
        //每次运行都会创建新的数据库
        protected override void Seed(CodeFirstContext context)
        {
            base.Seed(context);
        }
    }
View Code

   c.DropCreateDatabaseIfModelChanges: 如果在模型改变是,自动创建一个新的数据库,就可以用这个方法(在开发过程中非常有用)

public class CodeFirstInitializer : DropCreateDatabaseIfModelChanges<CodeFirstContext>
    {
        protected override void Seed(CodeFirstContext context)
        {
            base.Seed(context);
        }
    }
View Code

7.在App.config中添加链接数据库字符串

   <connectionStrings> 
    <add name="Context" connectionString="data source=hw-zhi-02;initial catalog=Test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
   <!--账号密码登入<add name="Context" connectionString="Data Source=myServerAddress;Initial Catalog=myDataBase;;User ID=sa;Password=!QAZ2wsx;Integrated Security=false;;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
View Code

8.打开NuGet控制台

  a.运行命令 enable-migrations

  运行成功后,有Migrations文件夹

  b.运行命令add-migration zhiyi

  运行成功后,会出现

  c.运行命令 update-database

  运行成功后,在数据库中可以看见新建的数据库和表

 

posted @ 2017-08-07 11:19  Yanzhiyi  阅读(704)  评论(0)    收藏  举报