asp.net core 使用EF7 Code First 创建数据库,同时使用命令创建数据库

1.首先下载vs2015的Asp.Net Core(RC2)的插件工具(https://www.microsoft.com/net/core#windows)
2.创建一个asp.net Core的项目,这里我创建一个最简单的项目,就是一个console,在这个基础上我准备一步一步搭建一个Asp.Net Core的项目

3.添加相关的依赖(mvc的依赖和EF的依赖)在projecr.json中:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "type": "build"
    },
    "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-rc2-release1",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "type": "build"
    },
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": "portable-net45+win8+dnxcore50"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "gcServer": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

4。在Startup.cs 文件中做如下修改:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace SmBlog
{
    public class Startup
    {

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");
            }
            );

        }
    }
}

现在并没有添加Ef的服务。

5.新建一个appsettings.json 文件用于项目相关配置,在Startup.cs中的log的配置,以及后来的EF数据库的配置都在这个文件中。

{
  "ConnectionStrings": {
    "PostgreSql": "User ID=postgres;Password=123456;Host=localhost;Port=5432;Database=smbloh"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

6.依照MVC5中的项目目录结构创建如Controllers 和Views和Models文件如下图所示,新建一个HomeController 和Index Action和Index的视图,用于测试。

7.用过dotnet的方式运行(dotnet 相当于之前的dnx) 看到这个结果说明mvc6项目搭建完成

8.开始Ef的操作。在Models中新建一个实体Article简单的给他三个字段

    public class Article
    {
        public int Id { set; get; }

        public string Title { set; get; }

        public string Description { set; get; }
    }

9.在Models中新建一个SMContext(ef上下文对象)代码如下:

 public class SMContext : DbContext
    {
        public SMContext(DbContextOptions option) : base(option)
        {

        }

        public DbSet<Article> Articles { set; get; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }

10.修改Startup.cs 文件。增加对Ef的支持:代码如下

     public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDbContext<SMContext>(option => option.UseNpgsql(Configuration.GetConnectionString("PostgreSql")));

        }

11.为了初始化数据库,在此新建一个SampleData类,在项目启动的时候,调用此类,进行数据库的初始化。代码如下:

namespace SmBlog.Models
{
    public class SampleData
    {
        public async static Task InitDB(IServiceProvider service)
        {
            var db = service.GetService<SMContext>();

            if (db.Database != null && db.Database.EnsureCreated())
            {


                Article article = new Article
                {
                    Title = "test",
                    Description = "SMBlog Test"
                };

                db.Articles.Add(article);
                await db.SaveChangesAsync();
            }
        }
    }
}

这个地方比较灵活,我们初始化创建数据库的时候可以插入一条数据,也可以不插入。我在这个地方插入了一条文章的数据。当然系统中有用户,插入管理员是比较适当的操作的。

12.再次修改Startup文件 调用SampleData 在加载项目的时候创建数据库 并初始化。代码如下:

  public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");
            }
            );

            await SampleData.InitDB(app.ApplicationServices);
        }

13.再次启动项目,我的数据已经创建成功,并且插入一条数据。如图:

14.数据库迁移 。当我们增加一个User实体,并且修改了Article的实体,现在要进行数据库的迁移,不是简单的把数据库删除重新建立。要保证原有的数据不变,修改数据库结构。

增加的User实体如下:

    public class User
    {
        public int Id { set; get; }

        public string UserName { set; get; }

        public string Password { set; get; }
    }

修改后的Article实体如下,加了个Label的字段

   public class Article
    {
        public int Id { set; get; }

        public string Title { set; get; }

        public string Description { set; get; }

        public string Label { set; get; }
}

在SMContext文件中,增加User的DbConetxt;

如下代码:

        public DbSet<User> Users { set; get; }

 

15.在vs的PM命令输入 Add-Migration newBook

成功后会在项目中产生一个Migrations文件夹。里面有个快照文件和一个迁移的文件。在此不扩展了。

在执行命令: Update-Database newBook 发现报错了

 

问题解决,不用SampleData来初始化数据库,用 Add-Migration init    Update-Database init 来初始化数据库。

 

 

注:也可以在cmd控制台输入命令来实现code first 

首先打开cmd 切换到项目的project.json 文件所在文件。执行如下命令

dotnet ef migrations add FirstMigration 
dotnet ef database update

 

posted @ 2016-05-19 00:41  nele  阅读(18749)  评论(6编辑  收藏  举报