Search code examples
c#asp.net-coreasp.net-web-apiasp.net-identity

Identity userManager.FindByNameAsync() returns null value


I'm upgrading an old project in ASP .Net 5 to ASP .Net 7 and when i try to use userManager.FindByNameAsync() it returns the following exception in the API Response :

System.Data.SqlTypes.SqlNullValueException: Data is Null. 
This method or property cannot be called on Null values.

knowing that it works with no problems in ASP .Net 5. Here is the full exception:

I tried to troubleshoot the problem using the Visual Studio debugger and set a breakpoint to track the value which should be stored in a variable called user containing the returned value from the database using userManager.FindByNameAsync().

When the cursor reaches the toggle point the error is thrown and the rest of the program stops debugging knowing that the value i'm passing to the function is correct! The user I'm looking for is created using userManager.CreateAsync() This is the model that i'm trying to get:

namespace API.Models
{
    public class User : IdentityUser<int>
    {
        public string FirstName { get; set; }

        //********** Visa Info**********
        public string ClientName { get; set; }
        public string BankName { get; set; }
        public int AccountNumber { get; set; }
        public string Section { get; set; }
        public int CardNumber { get; set; }
        public string CardName { get; set; }
        public int WalletNumber { get; set; }
        public string lastName { get; set; }
        public string address { get; set; }
        public string ImageID { get; set; } 
        public int TotalProfits { get; set; } = 0;
        public int WithdrawnProfits { get; set; } = 0;

        public virtual ICollection<Product> Products { get; set; }
        public virtual ICollection<Order> Orders { get; set; }
        public ICollection<UserRole> UserRoles { get; set; }
        public ICollection<WithdrawRequest> WithdrawRequests { get; set; }
        public virtual ICollection<UserBill> UserBills { get; set; }
    }
}

this is the function:

private async Task CreateAdmin()
        {
            var admin = await _userManager.FindByNameAsync("Admin");

            if (admin == null)
            {
                var newUser = new User
                {
                    Email = "[email protected]",
                    UserName = "Admin",
                    PhoneNumber = "0796544854",
                    EmailConfirmed = true
                };

                var createAdmin = await _userManager.CreateAsync(newUser, "1234");

                if (createAdmin.Succeeded)
                {
                    if (await _roleManager.RoleExistsAsync("Admin"))
                        await _userManager.AddToRoleAsync(newUser, "Admin");
                }

                var newShippCompany = new ShippingCompany
                {
                    Id = 1,
                    companyName = "Not Attached",
                    companyPhone = null
                };

                await _souqlyRepo.Add(newShippCompany);
                await _souqlyRepo.SaveAll();
            }
        }

And this is the error from the API Response: -

{System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
   at Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull()
   at Microsoft.Data.SqlClient.SqlBuffer.get_String()
   at Microsoft.Data.SqlClient.SqlDataReader.GetString(Int32 i)
   at lambda_method42(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByNameAsync(String userName)
   at API.Controllers.AuthController.CreateAdmin() in /Users/ahmedgamal/projects/API/Controllers/AuthController.cs:line 84
   at API.Controllers.AuthController.Login(UserForLogin userForLogin) in /Users/ahmedgamal/projects/API/Controllers/AuthController.cs:line 149
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Connection: keep-alive
Host: localhost:5077
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Content-Type: application/json-patch+json
Cookie: _xsrf=2|7ddc8933|478e981c349410ca2e05fa7b50dcaeee|1671139281; username-localhost-8888="2|1:0|10:1671456298|23:username-localhost-8888|44:NjA1OTkxOTgzZjFhNDE1MWFhOTIxNWQ3ZDczZjU1MjY=|5ae71afcdb82e897faa88c8158ab4ccb4edfbe7e4478f2e6dc88926938171b11"; .AspNetCore.Antiforgery._EomAn3AoJg=CfDJ8Oe9S8Poye1KncOFEtdCmBpov-Z4Szk20KKrAQTFIPoPKPabF-KF8zohP-BZVw8pL_FKLxPvrlxXrZt5K5SBF3YB9-5Lul_q0outcr2kZgyc4glteG-JGf8j0_pq2-a0_DN9WupHrzZo3igvLzqBsoQ; .AspNetCore.Session=CfDJ8Oe9S8Poye1KncOFEtdCmBr0c19qm2tGMZe7b6rkQbgsvt77HALStTx0XC86brZHEp8kf6YdM46RUT1wt0K6Wfa7mMXMXHE58ap382sIuQOtujORzTAnlBVLypOYMuJTwj%2BLmJ4lrUHWyY98ViOI9UdtLv1N6Nifn4%2BfUZE2I9QM
Origin: http://localhost:5077
Referer: http://localhost:5077/swagger/index.html
Content-Length: 116
sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
}

Solution

  • find this line in your csproj file and disable it

    <Nullable>enable</Nullable>
    

    it would be there by default in .net 6/7 but don't exist by default in .net 5,That's why you got the error in .net 7 but didn't get the error in .net 5

    You could check the related document for more details