It's the first time I'm working with Entity and Identity and I'm confused about how my user persists. Basically I have a User table, with several relationships with the database and the Id int) I have the Identity AspNetUsers table and AspNetRoles.
I'm trying to create a transaction to ensure that I will not create AspNetUsers without the User and still not add the selected Role in View to a DropDown that I called Profile.
I tried on my UserController the following, in the action create:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CriarUsuario(Usuario model)
{
if (ModelState.IsValid)
{
ApplicationUser identityUser = new ApplicationUser
{
UserName = model.LOGIN,
LOGIN = model.LOGIN,
};
using (GPSdEntitiesIdentity IdentityContext = new GPSdEntitiesIdentity())
{
using (var transaction = IdentityContext.Database.BeginTransaction())
{
var userStore = new UserStore<ApplicationUser>(IdentityContext);
var userManager = new UserManager<ApplicationUser>(userStore);
IdentityResult resultado = userManager.Create(identityUser, model.SENHA);
if (resultado.Succeeded)
{
resultado = userManager.AddToRole(identityUser.Id, model.Perfil);
if (resultado.Succeeded)
{
if (GravarNaTabelausuario(identityUser.Id, model))
{
transaction.Commit();
return RedirectToAction("Index", "Home");
}
}
}
transaction.Rollback();
ModelState.AddModelError("ErroIdentity", resultado.Errors.FirstOrDefault());
}
}
}
ViewBag.ReadOnly = false;
return View(model);
}
The code that persists in my User table is:
public bool GravarNaTabelausuario(string IdUsuario, Usuario model)
{
UsuarioEnt UsuarioEnt = new UsuarioEnt()
{
IdAspNetUsers = IdUsuario,
IdPessoa = model.UsuarioEnt.IdPessoa,
IdStatusRegistro = model.UsuarioEnt.IdStatusRegistro,
IdUnidade = model.UsuarioEnt.IdUnidade,
};
UsuarioNeg UsuarioApp = new UsuarioApp(null);
if (UsuarioNeg.RecebeRegistro(UsuarioEnt))
{
if(UsuarioNeg.ValidaRegistro())
{
if (UsuarioNeg.GravaRegistro(UsuarioEnt))
{
return true;
}
}
}
return false;
}
But it only works if I comment on the rows for creating the rollback transaction etc. With the transaction as it is I am having a connection timeout error hit. It appears that the transaction is blocking the table, preventing other inserts and validation queries from running. Can anyone identify where I'm going wrong?