2017-02-20 82 views
1

我創建了IBM Bluemix的ASP.NET核心項目,並添加到撰寫的連接爲MySQL MySQL database如何bluemix我的asp.net核心連接到MySQL遷移

我從克隆了一個項目數據庫在Visual Studio 2015的hub.jazz.com上使用git倉庫,我想從創建的上下文中生成數據庫,但我無法連接到數據庫。

using HunterViews.Domain.Entities; 
using System.Collections.Generic; 
using Microsoft.EntityFrameworkCore; 
using Microsoft.Extensions.Options; 

namespace HunterViews.Data 
{ 
    public class HunterViewsContext : DbContext 
    { 
     public HunterViewsContext(DbContextOptions<HunterViewsContext> options) : base(options) 
     { 
     } 

     public HunterViewsContext() 
     { 
     } 

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
     { 
     optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=HunterViewsCore;Trusted_Connection=true;"); 
     } 

     public DbSet<User> users { get; set; } 
     public DbSet<JobSeeker> jobseekers { get; set; } 
     public DbSet<HeadHunter> headHunters { get; set; } 
     public DbSet<Offer> offers { get; set; } 
     public DbSet<Post> posts { get; set; } 
     public DbSet<Skill> skills { get; set; } 
     public DbSet<Reclamation> reclamations { get; set; } 
     public DbSet<Evaluation> evaluations { get; set; } 
     public DbSet<Formation> formations { get; set; } 
     public DbSet<Notification> notifications { get; set; } 
     public DbSet<Certification> certifications { get; set; } 
    } 
}   

所以,我想改變optionsBuilder:optionsBuilder.UseSqlServer(@"Server(localdb)\mssqllocaldb;Database=HunterViewsCore;Trusted_Connection=true;");

使用我的Bluemix創建MySQL數據庫生成我的數據庫。我怎樣才能做到這一點?

回答

1

要使用MySQL而不是SQL Server,您需要在項目中包含MySQL providers for Entity Framework Core之一。在Visual Studio 2015中,這意味着修改您的project.json文件以包含依賴項。您添加的依賴關係取決於您選擇使用哪個提供程序。例如,如果您選擇使用SapientGuardian,你會增加SapientGuardian.EntityFrameworkCore.MySql您project.json的dependencies部分,像這樣:

"dependencies": { 
    "SapientGuardian.EntityFrameworkCore.MySql": "7.1.19" 
} 

用於ASP.NET中,標準的約定是做配置在Startup類,但你也可以像在發佈的示例中那樣在您的DbContext中配置數據庫連接字符串。要在Startup類配置(假設你的連接字符串存儲在一個名爲connectionString一個字符串變量,修改該行,您添加DbContext到這一點:

app.AddDbContext<HunterViewsContext>(options => options.UseMySQL(connectionString));

通過這樣做,你將不再需要重寫該OnConfiguring方法在DbContext。但是,如果你想在DbContext使用OnConfiguring相反,你可以簡單地調用optionsBuilder.UseMySQL(connectionString)有代替。

現在,這裏就是它變得有點棘手。由於撰寫了MySQL的服務使用自SIG ned SSL證書作爲代表VCAP_SERVICES環境變量中的PEM格式證書的Base64編碼字符串提供,您需要將該證書轉換爲PFX格式,然後才能將其用於MySQL提供程序。

您有兩個選擇來完成此轉換。第一個選擇是使用一些外部工具將證書轉換爲PFX格式,並將該文件與您的應用程序一起推送。另一種解決方案是在配置數據庫連接時,在應用程序啓動時即時轉換證書。

可以使用BouncyCastle的NuGet包做對飛的轉換,像這樣:

private static void CreatePfxFromPemCertificate(string base64encodedPem, string pfxFilePath, string pfxPassword) 
    { 
     // get the PEM certificate, then convert to pfx format 
     byte[] bytes = Convert.FromBase64String(base64encodedPem); 
     Pkcs12Store store = new Pkcs12StoreBuilder().Build(); 
     X509CertificateEntry[] chain = new X509CertificateEntry[1]; 

     object pemObject; 
     using (var streamReader = new StreamReader(new MemoryStream(bytes))) 
     { 
      PemReader pemReader = new PemReader(streamReader); 
      if ((pemObject = pemReader.ReadObject()) is X509Certificate) 
      { 
       chain[0] = new X509CertificateEntry((X509Certificate)pemObject); 
      } 
     } 

     store.SetCertificateEntry(pfxFilePath, chain[0]); 
     var certFile = File.Create(pfxFilePath); 
     store.Save(certFile, pfxPassword.ToCharArray(), new SecureRandom()); 
     certFile.Flush(); 
     certFile.Dispose(); 
    } 

此功能將要求這些using語句:

using Org.BouncyCastle.OpenSsl; 
using Org.BouncyCastle.Pkcs; 
using Org.BouncyCastle.Security; 
using Org.BouncyCastle.X509; 

而且這種依賴項目。JSON:

"Portable.BouncyCastle-Signed": "1.7.0.2", 

該函數接受3個參數:

  1. Base64編碼串(在VCAP_SERVICES環境變量提供)
  2. 到將要寫入
  3. 的PFX文件的路徑應該用來保護pfx文件的密碼

既然我們有一個函數c轉換Base64編碼的證書,是時候把它放在一起,並從Startup類中的VCAP_SERVICES環境變量創建連接字符串。

首先,在Startup類的構造函數:

public Startup(IHostingEnvironment env) 
{ 
    var builder = new ConfigurationBuilder() 
     .SetBasePath(env.ContentRootPath) 
     .AddJsonFile("vcap-local.json", optional:true); // when running locally, store VCAP_SERVICES credentials in vcap-local.json 

    Configuration = builder.Build(); 

    // try to get the VCAP_SERVICES environment variable (when running on Bluemix) 
    string vcapServices = Environment.GetEnvironmentVariable("VCAP_SERVICES"); 
    if (vcapServices != null) 
    { 
     JObject json = JObject.Parse(vcapServices); 
     var credentialsToken = json.SelectToken("compose-for-mysql")? // look for compose-for-mysql instance 
       .FirstOrDefault()?     // get first database instance 
       .SelectToken("credentials");  // get the credentials 
     // get the uri 
     Configuration["compose-for-mysql:0:credentials:uri"] = credentialsToken?.SelectToken("uri"); 
     // get the base64 certificate 
     Configuration["compose-for-mysql:0:credentials:ca_certificate_base64"] = credentialsToken?.SelectToken("ca_certificate_base64"); 
    } 
} 

此代碼將從VCAP_SERVICES環境變量搶數據庫開放的,或在您的項目目錄名爲vcap-local.json如果你正在本地運行一個JSON文件(您可以從Bluemix UI中的連接選項卡複製憑證)。

爲了把這個都聚集在你的ConfigureServices方法來創建數據庫字符串中的Startup類:

public void ConfigureServices(IServiceCollection services) 
{ 
    var databaseUri = Configuration["compose-for-mysql:0:credentials:uri"]; 
    var username = (databaseUri.Split('/')[2]).Split(':')[0]; 
    var password = (databaseUri.Split(':')[2]).Split('@')[0]; 
    var port = (databaseUri.Split(':')[3]).Split('/')[0]; 
    var hostname = (databaseUri.Split('@')[1]).Split(':')[0]; 
    var database = databaseUri.Split('/')[3]; 

    // create the connection string 
    var connectionString = $"Server={hostname};Port={port};uid={username};pwd={password};Database={database};SSL Mode=Required;"; 

    // convert the Base64 encoded PEM SSL certificate to PFX format 
    CreatePfxFromPemCertificate(config[$"compose-for-mysql:0:credentials:ca_certificate_base64"], 
     "compose-for-mysql0.pfx", password); 

    // add the ssl certificate to the connection string 
    connectionString += "CertificateFile=compose-for-mysql0.pfx;"; 
    connectionString += $"CertificatePassword={password};"; 

    // add database context 
    services.AddDbContext<HunterViewsContext>(options => options.UseMySQL(connectionString)); 

    // Add framework services. 
    services.AddMvc(); 
} 
+0

請使用BouncyCastle的,Portable.BouncyCastle官方便攜版。我是便攜式叉子的維護者。如果遇到問題,請在回購協議中打開一個問題:https://github.com/onovotny/bc-csharp –