Search code examples
c#asp.net-coreentity-framework-6asp.net-identity

How can I return my entity, after it has been inserted into the database?


I use a model class for the solution user and use identity to control login and etc.

So for me to create an Identity user I need the application user to be created first. How can I return this entity? Or, how can I return the Id was created?

Below my class structure

AuthController

 public class AuthControllerController : MainController
    {

        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;
        private readonly AppSettings _appSettings;
        private readonly IUserSolutionService _userSolutionService;
        private readonly IUserSolutionRepository _userSolutionRepo;
        private readonly IMapper _mapper;

        public AuthControllerController(IUserIdentity userIdentity,
                                        SignInManager<IdentityUser> signInManager,
                                        UserManager<IdentityUser> userManager,
                                        IOptions<AppSettings> appSettings,
                                        IUserSolutionService userSolutionService,
                                        IUserSolutionRepository userSolutionRepo,
                                        IMapper mapper) : base(userIdentity)
        {
            _signInManager = signInManager;
            _userManager = userManager;
            _appSettings = appSettings.Value;
            _userSolutionService = userSolutionService;
            _userSolutionRepo = userSolutionRepo;
            _mapper = mapper;
        }

        [HttpPost("register")]
        public async Task<ActionResult> Registrar(UserSolutionViewModel registerUser)
        {
            if (!ModelState.IsValid) return BadRequest("Há itens faltando");

            var returnOfRegisterUser = someMethodToReturnId(); //How to do this?

            var user = new IdentityUser()
            {
                Id = registerUser.Id.ToString(), //return the Id of User of App
                UserName = registerUser.Email, //não precisa ser o email, mas, por padrao deixaremos ser o email
                Email = registerUser.Email,
                EmailConfirmed = true //pode ser false e ter a confirmação de email em algum lugar.                

            };            

            var result = await _userManager.CreateAsync(user, registerUser.Password);

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, false); //FALSE neste parametro é se quer persistir esse login
                //return CustomResponse(GerarJwtClaimsAndUser(user.Email)); // este metodo retorna mais dados do usuário e não somente o Token
                //return CustomResponse(GerarJwt());//caso seja necessário gerar o token com as claims, usar o outro método - linha abaixo - 
                return  Ok(GerarJwt());
            }

            return Ok(registerUser);
        }        
}

Interface:

public interface IUserSolutionRepository : IRepository<UserSolution>
{       
    Task<UserSolution> GetUserByEmail(string email);
    Task<UserSolution> GetUserByPhone(string countryCode, string areaCode, string phone);
    Task<UserSolution> GetUser(Guid id);
    Task<UserSolution> GetUserAddress(Guid id);
    Task<UserSolution> AddUserSolution(UserSolution user);

}

Repo:

 public class UserSolutionRepository : Repository<UserSolution>, IUserSolutionRepository
    {
        public UserSolutionRepository(SolutionDbContext context) : base(context)
        {
            
        }

        ......

        public async Task<UserSolution> AddUserSolution(UserSolution user)
        {
            //Can I return here????
        }
    }
}

Once added the user in the database would need, I believe, only the Id that was generated in the database to insert in Identity. Thank you for your help.


Solution

  • If you are using DB generated Ids (like IDENTITY), Id will be automatically filled after SaveChangesAsync() for you:

        public async Task<IActionResult> Create(User user)
        {
            int id = user.Id; // id is 0
    
            _context.Add(user); 
            await _context.SaveChangesAsync();
    
            id = user.Id;     // Yes, it has value  
            return View(user);
        }
    

    Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

    Screenshots of test

    enter image description here

    Before insert user

    enter image description here

    After insert user

    enter image description here