繁体   English   中英

在.NET Core 2,Mac OS,使用MySQL的Visual Studio for Mac上:ArgumentOutOfRangeException:长度不能小于零

[英]On .NET Core 2, Mac OS, Visual Studio for Mac using MySQL: ArgumentOutOfRangeException: Length cannot be less than zero

我正在MacOS的.NET Core上做一个简单的测试。

我在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'

完成此操作后,我从MacOS在Visual Studio上创建了类型为Core Web API的项目。

这是我的模型表示:

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方法以在DB上进行搜索。

但我收到此错误消息:

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

谢谢!

我分三步解决了这个问题:

1)删除所有NuGets软件包,除了:

Microsoft.AsoNetCore.All
Pomelo.EntityFrameworkCore.MySql
Pomelo.EntityFrameworkCore.MySql.Design

2)在Startup.cs中的机会:

options.UseMySQL(connection)

对于:

options.UseMySql(connection)

3)在filds GENDER和ACTIVE中将CHAR(1)的列类型更改为VARCHAR(1)。 因为经过上述两个步骤后,抛出了一个异常说:

System.InvalidOperationException: An exception occurred while reading a database value. The expected type was 'System.Char' but the actual value was of type 'System.String'. ---> System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte'.

谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM