Mysql和Visual Studio 2019 for macOS之间的连接不起作用

时间:2019-09-19 06:39:13

标签: c# mysql .net database-connection visual-studio-2019

我正在尝试使用适用于macOS的Visual Studio 2019开发Web应用程序(.net核心MVC),并作为数据库使用Mysql。

我一直在寻找视频,网站,告诉您如何建立连接,但所有尝试均失败。

我将向您展示我的代码:

NuGet软件包:

  • Microsoft.AspNetCore.App(2.1.1)
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore(2.1.1)
  • Microsoft.AspNetCore.Razor.Design(2.1.2)
  • Microsoft.EntityFrameworkCore.Tools(2.1.1)
  • Mysql.Data
  • Mysql.Data.EntityFrameworkCore(8.0.17)

SDK:

  • MicrosoftNETCore.App(2.1.0)

    // Data Access Object -> MysqlContext.cs :

    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Configuration;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using MySql.Data.MySqlClient;
    using VideoClubSharp.Models;


    namespace VideoClubSharp.DAO
    {
        public class MysqlContext : IdentityDbContext<AplicationUser>
        {
            public string ConnectionString { get; set; }

            public MysqlContext(DbContextOptions<MysqlContext> options) : base(options)
            {
                this.Database.EnsureCreated();
            }

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

            private MySqlConnection GetConnection()
            {
                return new MySqlConnection(ConnectionString);
            }

            public List<ActorMO> GetActorMOs()
            {
                var Result = new List<ActorMO>();

                using(MySqlConnection db = GetConnection())
                {
                    db.Open();
                    MySqlCommand query = new MySqlCommand("select * from Actor", db);
                    using (MySqlDataReader row = query.ExecuteReader())
                    {
                        while (row.Read())
                        {
                            int idActor = row.GetInt32("idActor");
                            string FullName = row.GetString("FullName");
                            char Sex = row.GetChar("Sex");
                            Result.Add(new ActorMO(idActor, FullName, Sex));
                        }
                    }
                }

                return Result;
            }
        }
    }

    // Models -> ActorMO & AplicationUser;

    // ActorMO.cs:

    using System;

    namespace VideoClubSharp.Models
    {
        public class ActorMO 
        {
            public int idActor { get; set; }
            public string FullName { get; set; }
            public char Sex { get; set; }

            public ActorMO(int idActor, string FullName, char Sex) 
            {
                this.idActor = idActor;
                this.FullName = FullName;
                this.Sex = Sex;
            }
        }
    }


    // AplicationUser.cs: 

    using System;
    using Microsoft.AspNetCore.Identity;


    namespace VideoClubSharp.Models
    {
        public class AplicationUser : IdentityUser
        {
            public AplicationUser()
            {
            }
        }
    }

    // appsettings.json
    {
      "Logging": {
        "IncludeScopes":  false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionString" :  {
        "MysqlConnection" :  "server@localhost; userid=root; password=****; port=3306: datanase=VideoClub; sslmode=none;"
      }
    }

    // Startup.cs

    namespace VideoClubSharp
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            public IConfiguration Configuration { get; }

            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });

                services.AddDbContext<MysqlContext>(options => options.UseMySQL(Configuration.GetConnectionString("MysqlConnection")));
                services.AddIdentity<AplicationUser, IdentityRole>().AddEntityFrameworkStores<MysqlContext>().AddDefaultTokenProviders();
                //services.Add(new ServiceDescriptor(typeof(mysqlContext), new mysqlContext(Configuration.GetConnectionString("MysqlConnection"))));
                services.AddMvc();
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseCookiePolicy();

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

    // ActorController.cs     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using VideoClubSharp.DAO;
    using VideoClubSharp.Models;

    // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

    namespace VideoClubSharp.Controllers
    {
        public class ActorController : Controller
        {
            public IActionResult Index()
            {
                MysqlContext Data = HttpContext.RequestServices.GetService(typeof(MysqlContext)) as MysqlContext;
                return View(Data.GetActorMOs().ToList()) ;
            }
        }
    }



     //And I've put an ActionLink in Home page, to see the Actors from //Database, but show the next error:


    An unhandled exception occurred while processing the request.

    ArgumentNullException: Value cannot be null.
    Parameter name: connectionString
    Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName)



    ArgumentNullException: Value cannot be null. Parameter name: connectionString
    Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName)
    Microsoft.EntityFrameworkCore.Infrastructure.RelationalOptionsExtension.WithConnectionString(string connectionString)
    Microsoft.EntityFrameworkCore.MySQLDbContextOptionsExtensions.UseMySQL(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<MySQLDbContextOptionsBuilder> MySQLOptionsAction)
    VideoClubSharp.Startup.<ConfigureServices>b__4_1(DbContextOptionsBuilder options) in Startup.cs
    +
                services.AddDbContext<MysqlContext>(options => options.UseMySQL(Configuration.GetConnectionString("MysqlConnection")));
    Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions+<>c__DisplayClass1_0<TContextService, TContextImplementation>.<AddDbContext>b__0(IServiceProvider p, DbContextOptionsBuilder b)
    Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory<TContext>(IServiceProvider applicationServiceProvider, Action<IServiceProvider, DbContextOptionsBuilder> optionsAction)
    Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions+<>c__DisplayClass10_0<TContextImplementation>.<AddCoreServices>b__0(IServiceProvider p)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(IServiceCallSite callSite, TArgument argument)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
    VideoClubSharp.Controllers.ActorController.Index() in ActorController.cs
    +
                MysqlContext Data = HttpContext.RequestServices.GetService(typeof(MysqlContext)) as MysqlContext;
    lambda_method(Closure , object , object[] )
    Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
    Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
    Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
    Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

2 个答案:

答案 0 :(得分:0)

我相信这在MacO上是不可能的。我如何实现它的方法是安装Docker并在其中使用带有SQL Server的容器。然后,您可以连接到该服务器。

以下链接可能对您有用:https://www.sqlpassion.at/archive/2018/11/19/running-sql-server-with-docker-on-the-mac/

答案 1 :(得分:0)

您的例外是:

df <- data.frame(V1= c("SF", "SF", "NYC"),
    V1_1 = c(1990, 2000, 1990),
    V1_10 = 1:3, V1_2 = 1:3, V2 = 1:3)

问题是您传递给V1, V1_1, V1_2, V1_10, V2 的{​​{1}}的值是ArgumentNullException: Value cannot be null. Parameter name: connectionString Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(string value, string parameterName) at Microsoft.EntityFrameworkCore.Infrastructure.RelationalOptionsExtension.WithConnectionString(string connectionString) at Microsoft.EntityFrameworkCore.MySQLDbContextOptionsExtensions.UseMySQL(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<MySQLDbContextOptionsBuilder> MySQLOptionsAction) at VideoClubSharp.Startup.<ConfigureServices>b__4_1(DbContextOptionsBuilder options) in Startup.cs

其为connectionString的原因是您在UseMySQL中有一个错误。根据{{​​3}},密钥名称需要为 null ,而不是null。您的appsettings.json应该是:

ConnectionStrings

此外,您的连接字符串中有错别字。进行以下更改:

  • ConnectionString而非appsettings.json
  • // appsettings.json { ... "ConnectionStrings": { "MysqlConnection": "server=localhost; userid=root; password=****; port=3306; database=VideoClub; sslmode=none;" } } 而非server=localhost;
  • server@localhost;而非port=3306;

有关连接字符串选项的完整参考,请参见https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings#aspnet-core