首页 > 解决方案 > 无法将“System.DBNull”类型的对象转换为“System.Int32”类型的 ASP.NET

问题描述

我正在尝试学习如何使用 ASP.NET 开发 API。一切都很顺利,直到我尝试在外键之间连接 2 个表。所以我阅读了这篇文档以了解如何使用外键。我的用户对象是这样的:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using MyApp.Utils;


namespace MyApp.Models.DataModels
{
    public abstract class UserBase
    {
        [Key]
        public int id_usr { get; set; }

        public string name_usr { get; set; }
        public string surname_usr { get; set; }
        [EmailAddress]
        public string email_usr { get; set; }
        public int fk_prf_usr { get; set; }
        [ForeignKey("fk_prf_usr")]
        public ProfileModel profile { get; set; }
    }

    public class DbUser : UserBase
    {
        private string _password;
        public string password_usr
        {
            get
            {
                return _password;
            }
            set
            {
                _password = value.StrongHash();
            }
        }
    }
}

当我运行它并尝试获取用户时,它会显示此页面:

An unhandled exception occurred while processing the request.

InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Int32'.
MySqlConnector.Core.Row.GetInt32(int ordinal) in C:\projects\mysqlconnector\src\MySqlConnector\Core\Row.cs, line 177

Stack Query Cookies Headers
InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Int32'.
MySqlConnector.Core.Row.GetInt32(int ordinal) in C:\projects\mysqlconnector\src\MySqlConnector\Core\Row.cs
lambda_method(Closure , DbDataReader )
Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable<T>+AsyncEnumerator.BufferlessMoveNext(DbContext _, bool buffer, CancellationToken cancellationToken)
Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.ExecuteAsync<TState, TResult>(TState state, Func<DbContext, TState, CancellationToken, Task<TResult>> operation, Func<DbContext, TState, CancellationToken, Task<ExecutionResult<TResult>>> verifySucceeded, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable<T>+AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
System.Linq.AsyncEnumerable+SelectEnumerableAsyncIterator<TSource, TResult>.MoveNextCore(CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Select.cs
System.Linq.AsyncEnumerable+AsyncIterator<TSource>.MoveNext(CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\AsyncIterator.cs
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor<T>+EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
System.Linq.AsyncEnumerable.Aggregate_<TSource, TAccumulate, TResult>(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, Func<TAccumulate, TResult> resultSelector, CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Aggregate.cs
JoinUpp.API.Controllers.UsersController.GetUsers() in UsersController.cs
+
            return await _context.user_usr.ToListAsync();
lambda_method(Closure , object )
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
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.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

而且我不知道如何解决这个问题,我希望有人可以帮助我解决这个问题。我认为这取决于这一行:

public int fk_prf_usr { get; set; }
[ForeignKey("fk_prf_usr")]
public ProfileModel profile { get; set; }

因为如果我评论这一行,我的 API 就可以工作。

标签: c#asp.netentity-frameworkapi

解决方案


推荐阅读