我正在尝试使用Visual Studio 2019 for macOS开发Web应用程序(.net core 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)
您的例外情况是:
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
问题是您传递给UseMySQL
的connectionString
值是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 连接选项。
我相信这在MacOS上是不可能的。我是如何实现它的,那就是安装 Docker 并使用一个带有 SQL 服务器的容器。然后,您可以与此服务器连接。
也许以下链接对您有用:https://www.sqlpassion.at/archive/2018/11/19/running-sql-server-with-docker-on-the-mac/