DotNetCore中使用EF下Migration


  以前使用db.Database.EnsureCreatedAsync()创建数据库,这样创建的数据库无法更新,无法迁移,当数据库作出修改后就会因为兼容旧版而束手无策,只能重新录入数据。基于这种需求,研究了EF提供的Migrations功能。

  vs版本:2015,.NetCore版本:1.0.1。

  新建项目ConsoleApp1。

  想要使用Migrations,需先安装EF命令行工具:Microsoft.EntityFrameworkCore.Tools,不知道什么时候,此包被包含到“Microsoft.EntityFrameworkCore.Tools.DotNet”中:

"tools": {
    "Microsoft.EntityFrameworkCore.Tools.DotNet": {
      "version": "1.0.0-preview3-final"
    }

注:经调查,此包版本须为“1.0.0-preview3-final”,否则各种失败。

  其他需要引用的包有:

    "Microsoft.EntityFrameworkCore.Design": {
      "version": "1.0.1",
      "type": "build"
    },
    "System.Reflection.TypeExtensions": "4.3.0-*",
    "Microsoft.EntityFrameworkCore": "1.0.1-*",

注:Microsoft.EntityFrameworkCore.Design的版本不可低于1.0.0-preview3-final,不可高于1.0.1。

  接下来可以安装工具了,在ConsoleApp1解决方案根目录使用命令:

dotnet restore
cd src\\ConsoleApp1
dotnet ef

  成功后命令行显示:

  此时已可使用EF命令行了。

  现在创建Model:

    public class Blog
    {
        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual string Url { get; set; }
    }

    public class Post
    {
        public virtual int Id { get; set; }

        public virtual string Title { get; set; }

        public virtual string Content { get; set; }

        public virtual int BlogId { get; set; }

        public virtual Blog Blog { get; set; }
    }

  创建数据上下文:

  public class EFCoreContext : DbContext
    {public DbSet<Blog> Blog { get; set; }

        public DbSet<Post> Post { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("data source=consoledemo.sdb");
        }
    }

  在工程所在目录使用命令:

  此时输出目录中已生成了数据库文件,并自动创建了两个表Blog和Post。

  添加数据:

                var blog = new Blog
                {
                    Id = 11,
                    Name = "myblog",
                    Url = "http://www.cnblogs.com/automan-wei/"
                };

                db.Blog.Add(blog);
                db.SaveChanges();    

  显然是成功的。

  现在使用数据库迁移。

  修改Blog类,添加一个属性:

  public class Blog
    {
        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual string Url { get; set; }

        public virtual string Auther { get; set; }
    }

  需要先添加一个迁移,再更新数据库:

  可以看到,项目中已多出一个迁移文件:

  数据库也已被更新:

  关于EF7的数据库迁移功能,暂时就到这儿了。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM