Я страдаю, чтобы сделать простой тест на .NET Core на MacOS.
Я создал таблицу на MySQL:
CREATE TABLE USER (
ID BIGINT(20) NOT NULL AUTO_INCREMENT,
USERNAME VARCHAR(50) NOT NULL,
FIRSTNAME VARCHAR(50) NOT NULL,
MIDDLEINITIALS VARCHAR(10) NULL,
LASTNAME VARCHAR(50) NOT NULL,
PASSWORD VARCHAR(64) NOT NULL,
GENDER CHAR(1) NULL,
ACTIVE CHAR(1) NOT NULL,
CONSTRAINT USER_PK PRIMARY KEY (ID),
CONSTRAINT USER_UK UNIQUE KEY (USERNAME)
) ENGINE=InnoDB;
Вставлено несколько значений:
SELECT * FROM User;
1,'SYSTEM','SYSTEM',NULL,'ADMIN','senha123',NULL,'Y'
2,'JMICHEL','JEAN','J','MICHEL','senha123','M','Y'
После этого я создал проект типа Core Web API в Visual Studio из MacOS.
Это моё модельное представление:
using System;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WEB_API_DOT_NET_CORE.Model
{
[Table("User")]
public class UserModel
{
private Int64 id;
private String username;
private String firstName;
private String middleInitials;
private String lastName;
private String password;
private char gender;
private char active;
[Key]
public Int64 Id {
set { this.id = value; }
get { return this.id; }
}
[StringLength(50)]
public String Username {
set { this.username = value; }
get { return this.username; }
}
[StringLength(50)]
public String FirstName
{
set { this.firstName = value; }
get { return this.firstName; }
}
[StringLength(10)]
public String MiddleInitials {
set { this.middleInitials = value; }
get { return this.middleInitials; }
}
[StringLength(50)]
public String LasttName {
set { this.lastName = value; }
get { return this.lastName; }
}
[StringLength(64)]
public String Password {
set { this.password = value; }
get { return this.password; }
}
public char Gender {
set { this.gender = value; }
get { return this.gender; }
}
public char Active {
set { this.active = value; }
get { return this.active; }
}
public UserModel()
{
}
}
}
Мой контекст:
using System;
using Microsoft.EntityFrameworkCore;
namespace WEB_API_DOT_NET_CORE.Model
{
public class CollectionsCatalogContex: DbContext
{
public CollectionsCatalogContex(DbContextOptions<CollectionsCatalogContex> options): base(options)
{
}
public DbSet<UserModel> UsersModel { get; set; }
}
}
AppSettings:
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"MySQLConnString": {
"MySqlConnectionString": "Server=localhost;Port=3306;DataBase=COLLECTIONSCATALOG;Uid=root;Pwd=senha@321"
}
}
И на startup.cs:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration["MySQLConnString:MySqlConnectionString"];
services.AddDbContext<CollectionsCatalogContex>(options =>
options.UseMySQL(connection)
);
services.AddMvc();
}
Сейчас я пытаюсь создать контроллер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WEB_API_DOT_NET_CORE.Model;
namespace WEB_API_DOT_NET_CORE.Controllers
{
[Route("api/[controller]")]
public class UserController : Controller
{
private readonly CollectionsCatalogContex context;
public UserController(CollectionsCatalogContex context)
{
this.context = context;
}
// GET: api/values
[HttpGet]
public IEnumerable<UserModel> Get()
{
return context.UsersModel.ToList<UserModel>();
}
// GET api/user/2
[HttpGet("{id}")]
public UserModel Get(int id)
{
return context.UsersModel.Find(id);
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
Где я изменил методы get для поиска в БД.
Но я получил это сообщение об ошибке:
An unhandled exception occurred while processing the request.
ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
string.Substring(int startIndex, int length)
TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.
MySql.Data.MySqlClient.MySqlConfiguration.get_Settings()
TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
MySql.Data.MySqlClient.Replication.ReplicationManager.IsReplicationGroup(string groupName)
Я не знаю, в чем проблема!
Кто-нибудь может дать мне совет?
стек комплета:
TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
MySql.Data.MySqlClient.Replication.ReplicationManager.IsReplicationGroup(string groupName)
MySql.Data.MySqlClient.MySqlConnection.Open()
Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(bool errorsExpected)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+Enumerator.BufferlessMoveNext(bool buffer)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+Enumerator.MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+<_TrackEntities>d__17.MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+ExceptionInterceptor+EnumeratorExceptionInterceptor.MoveNext()
System.Collections.Generic.List.AddEnumerable(IEnumerable<T> enumerable)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
WEB_API_DOT_NET_CORE.Controllers.UserController.Get() in UserController.cs
-
}
// GET: api/values
[HttpGet]
public IEnumerable<UserModel> Get()
{
return context.UsersModel.ToList<UserModel>();
}
// GET api/user/2
[HttpGet("{id}")]
public UserModel Get(int id)
{
lambda_method(Closure , object , Object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, Object[] parameters)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
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>d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
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>d__17.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
Спасибо!