I have stucked with a problem to add UserId property from my ApplicationUser to domain Player entity.
This is my domain entity Player, where I have virtual ApplicationUserId property. I had an idea to write UserId after I created User in UserService, but could't proceed because of protection level of setter. Should I change remove protection level or there is another approach to achive result?
Maybe I should create a method in domain like SetUserId where I will set private property with UserId came from IdentityServer.CreateUser? Does it good approach?
public class Player: MyEntity
{
public string UserName { get; private set; }
public virtual Guid ApplicationUserId { get; private set; }
private Player()
{ }
}
UserService.cs snippet where user is creating
public async Task<(AppSignInResult result, SignInData data)> CreateUser(string username, string password, string email, string country)
{
var user = new ApplicationUser() { UserName = username, Email = email};
var result = await _userManager.CreateAsync(user, password);
...
// here is call of mediatr command
var command = new CreatePlayerCommand(username, country);
var id = await _mediator.Send(command);
...
return ...
}
CreatePlayerCommand.Handle handler code
public async Task<int> Handle(CreatePlayerCommand request, CancellationToken cancellationToken)
{
var player = new Player(
request.userName);
_unitOfWork.Players.Add(player);
await _unitOfWork.SaveChanges();
return player.Id;
}
CodePudding user response:
Why do you need to set Player.ApplicationUserId? You can generate it in the constructor or in DB. Why do you change the Id? If you access only from CreateUser command, you don't need it. Because the id is not coming from the client. You should generate automatically like that:
Player(string userName, ...)
{
ApplicationUserId = Guid.NewGuid();
UserName = userName;
...
}
CodePudding user response:
I've created method in domain entity
private void SetUserId(Guid userId)
{
ApplicationUserId = userId;
}
And passing in CreatePlayerCommand
and passing user id from _userManager.CreateAsync
result. It works like desired.