I have a Players
table in a SQL Server database and I'm trying to link it to the AspNetUsers
table with a stored procedure during registration. However, when I attempt to call the procedure, this variable p is null. I'm new to this kind of coding, so please keep that in mind when responding.
Here's the section where the variable p is null from the Register.cshtml.cs file -
readonly PlayerInitClass p;
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationIdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
int pID = await p.InitPlayerAsync(user);
}
}
Here is the class I created -
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Scorekeeper.Data;
namespace Scorekeeper.Areas.Identity
{
public class PlayerInitClass
{
private readonly ApplicationDbContext _db;
public PlayerInitClass(ApplicationDbContext db)
{
_db = db;
}
public async Task<Int32> InitPlayerAsync(ApplicationIdentityUser user)
{
int AspNetUserId = user.Id;
SqlParameter[] @params =
{
new SqlParameter("@returnVal", SqlDbType.Int) {Direction = ParameterDirection.Output},
new SqlParameter("@AspNetUserId", SqlDbType.Int) {Direction = ParameterDirection.Input, Value = AspNetUserId},
};
await _db.Database.ExecuteSqlRawAsync("EXEC @returnVal=[dbo].[InitializeNewRegistrationPlayer] @AspNetUserId", @params);
int result = Convert.ToInt32(@params[0].Value);
await Task.FromResult(result);
return result;
}
}
}
Here is the warning message I'm seeing about the Field p being null.
I ended up finding a way to not be null. As you can probably already tell, I am a newb and am blindly stumbling my way through this. That being said, I wouldn't feel comfortable saying this is the "right" answer to the question. Also, even though I got it to not be null it throws a different error now. If I can't figure it out I'll post a separate question.
Here is what I changed the PlayerInitClass to:
public class PlayerInitClass : Microsoft.EntityFrameworkCore.DbContext
{
public PlayerInitClass()
{
this.context = context;
}
public PlayerInitClass context { get; set; }
And this is how I instantiated it (not sure if that's the right way to say it):
PlayerInitClass p = new PlayerInitClass();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.