Identity userManager.FindByNameAsync() returns null value

Ahmed Gamal 11 Reputation points
2023-01-04T14:54:40.727+00:00

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 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 = "admin@admin.com",  
                    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.SingleQueryingEnumerable1.AsyncEnumerator.MoveNextAsync() at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsyncTSource
at Microsoft.AspNetCore.Identity.UserManager1.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, ValueTask1 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  
}  
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,207 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ahmed Gamal 11 Reputation points
    2023-01-05T09:32:12.79+00:00

    The Answer is by changing this line in the csproj file
    <Nullable>enable</Nullable>
    it is there by default starting from asp .net 6 and that is why it was working with me in asp .net 5
    Thanks for all the contributors
    @AgaveJoe
    @Zhi Lv - MSFT

    2 people found this answer helpful.
    0 comments No comments