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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM