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

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

我正在尝试使用 Visual Studio 2019 for macOS 开发 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)

开发工具包:

  • 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)

最佳答案

你的异常(exception)是:

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

问题是您传递给 UseMySQLconnectionString 值为 null

它为 null 的原因是您在 appsettings.json 中有错误。根据 https://learn.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 Connection Options有关连接字符串选项的完整引用。

关于c# - Mysql 和 Visual Studio 2019 for macOS 之间的连接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58005069/

相关文章:

c# - 使用 MSTest 和 Fakes (Shim) 填充 .Net System.Windows.Forms.Screen 构造函数以进行单元测试

c# - 如何在 MVVM WPF 应用程序中控制列表框的滚动位置

.net - 下载 .NET 4 源代码

c# - 如果事件在 .NET 中作为委托(delegate)实现,那么 .event IL 部分的意义何在?

c# - 由于缺少引用,无法将应用程序洞察支持添加到 azure webjob

c# - 无法将匿名类型传递给泛型构造函数

mysql - LIKE mysql查询完整单词

java - MYSQLjava.sql.SQLException : No suitable driver

php - 从数据库中获取用户的所有记录