Соединение между Mysql и Visual Studio 2019 для macOS не работает - PullRequest
1 голос
/ 19 сентября 2019

Я пытаюсь разработать веб-приложение (.net core MVC) с Visual Studio 2019 для macOS, и в качестве базы данных я использую Mysql.

Я искал видео, сайты, где рассказывают, какустановить соединение, но все попытки не увенчались успехом.

Я покажу вам свой код:

Пакеты NuGet:

  • Microsoft.AspNetCore.App (2.1.1)
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore (2.1.1)
  • Microsoft.AspNetCore.Razor.Design (2.1.2)
  • Microsoft.EntityFrameworkCore.Инструменты (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 голосов
/ 19 сентября 2019

Исключение составляют:

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, равно null.

Причина в том, что nullчто у вас есть ошибка в appsettings.json.Согласно https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings#aspnet-core, имя ключа должно быть 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; вместо port=3306:
  • database=VideoClub; вместо datanase=VideoClub;

См. Параметры подключения MySQL для полной ссылки на параметры строки подключения.

0 голосов
/ 19 сентября 2019

Я считаю, что это невозможно на MacOs.Как я этого добился, хотя устанавливал Docker и использовал контейнер с SQL-сервером.Затем вы можете подключиться к этому серверу.

Возможно, следующая ссылка может быть вам полезна: https://www.sqlpassion.at/archive/2018/11/19/running-sql-server-with-docker-on-the-mac/

...