Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将bluemix中的asp.net核心连接到Mysql以迁移数据库_Mysql_Asp.net Core_Ibm Cloud_Asp.net Core 1.0 - Fatal编程技术网

如何将bluemix中的asp.net核心连接到Mysql以迁移数据库

如何将bluemix中的asp.net核心连接到Mysql以迁移数据库,mysql,asp.net-core,ibm-cloud,asp.net-core-1.0,Mysql,Asp.net Core,Ibm Cloud,Asp.net Core 1.0,我在IBMBlueMix中创建了一个ASP.NET核心项目,并添加了一个到ComposeforMySQL的连接 我在Visual Studio 2015中从hub.jazz.com上的git存储库克隆了该项目,我想从我创建的上下文生成数据库,但我无法连接到数据库 using HunterViews.Domain.Entities; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Mi

我在IBMBlueMix中创建了一个ASP.NET核心项目,并添加了一个到ComposeforMySQL的连接

我在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; }
    }
}        
使用HunterViews.Domain.Entities;
使用System.Collections.Generic;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Options;
名称空间HunterViews.Data
{
公共类HunterViewContext:DbContext
{
公共HunterViewContext(DbContextOptions选项):基本(选项)
{
}
公共HunterViewContext()
{
}
配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
{
optionsBuilder.UseSqlServer(@“服务器=(localdb)\mssqllocaldb;数据库=HunterViewsCore;可信连接=true;”;
}
公共数据库集用户{get;set;}
公共数据库集求职者{get;set;}
公共数据库集猎头{get;set;}
公共DbSet提供{get;set;}
公共DbSet posts{get;set;}
公共数据库集技能{get;set;}
公共数据库集填海{get;set;}
公共数据库集求值{get;set;}
公共数据库集{get;set;}
公共数据库集通知{get;set;}
公共DbSet证书{get;set;}
}
}        
因此,我想更改选项生成器:
optionsBuilder.UseSqlServer(@“Server(localdb)\mssqllocaldb;Database=HunterViewsCore;Trusted_Connection=true;”


使用我在Bluemix上创建的MySQL数据库生成我的数据库。如何做到这一点?

要使用MySQL而不是SQL Server,您需要在项目中包含一个for Entity Framework核心。在Visual Studio 2015中,这意味着修改project.json文件以包含依赖项。您添加的依赖项取决于您选择使用的提供程序。例如,如果您选择使用,您将向您的项目添加
SapientGuardian.EntityFrameworkCore.MySql
。json的
依赖项
部分如下:

"dependencies": {
  "SapientGuardian.EntityFrameworkCore.MySql": "7.1.19"
}
ASP.NET Core的标准约定是在
Startup
类中进行配置,但您也可以在
DbContext
中配置数据库连接字符串,就像您在发布的示例中所做的那样。要在
Startup
类中进行配置(假设您的连接字符串存储在名为
connectionString
的字符串变量中),请修改将
DbContext
添加到其中的行:

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

通过这样做,您将不再需要覆盖
DbContext
中的
onconfigurang
方法。但是,如果您想在
DbContext
中使用
onconfigurang
,您只需在那里调用
optionsBuilder.UseMySQL(connectionString)

现在有点棘手了。由于Compose for MySQL服务使用自签名SSL证书,该证书作为Base64编码字符串提供,表示VCAP_services环境变量中的PEM格式证书,因此需要将该证书转换为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 Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
project.json中的依赖关系:

"Portable.BouncyCastle-Signed": "1.7.0.2",
此函数接受3个参数:

  • Base64编码字符串(在VCAP_服务环境变量中提供)
  • 将要写入的pfx文件的路径
  • 应用于保护pfx文件的密码
  • 现在我们有了一个可以转换Base64编码证书的函数,现在是时候把它放在一起,从
    Startup
    类中的
    VCAP\u SERVICES
    环境变量创建连接字符串了

    首先,在
    启动
    类的构造函数中:

    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");
        }
    }
    
    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();
    }
    
    此代码将从
    VCAP_SERVICES
    环境变量中获取数据库Uri,或者如果您在本地运行,则从项目目录中获取名为
    VCAP local.json
    的json文件(您可以从Bluemix UI中的connections选项卡复制凭据)

    要将所有这些放在一起,在
    启动
    类中的
    ConfigureServices
    方法中创建数据库字符串,请执行以下操作:

    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");
        }
    }
    
    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();
    }
    
    public void配置服务(IServiceCollection服务)
    {
    var-databaseUri=Configuration[“为mysql编写:0:凭据: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];
    //创建连接字符串
    var connectionString=$“服务器={hostname};端口={Port};uid={username};pwd={password};数据库={Database};SSL模式=必需;”;
    //将Base64编码的PEM SSL证书转换为PFX格式
    CreatePfxFrompCertificate(配置[$“为mysql编写:0:凭据:ca_certificate_base64”],
    “compose-for-mysql0.pfx”,密码);
    //将ssl证书添加到连接字符串
    connectionString+=“CertificateFile=compose-for-mysql0.pfx;”;
    connectionString+=$“CertificatePassword={password};”;
    //添加数据库上下文
    services.AddDbContext(options=>options.UseMySQL(connectionStri