![](/img/trans.png)
[英]ASP.NET Applicationuser ICollection Entity insert UserId null
[英]ASP.NET Core - How to insert ApplicationUser id in IdentityDbContext into Employee Model as UserId
在 ASP.NET 核心 Web ASPI 中,我正在實現 IndentityDbContext 和 Employee Model:
public Employee FromEmployeeCreateDtoToEmployee(EmployeetCreateDto employeeCreateDto)
{
if (employeeCreateDto == null)
{
return null;
}
return new Employee
{
EmployeeName = employeeCreateDto.EmployeeName,
AccountNumber = employeeCreateDto.AccountNumber,
Password = "12345",
ConfirmPassword = "12345",
Email = employeeCreateDto.Email,
UserName = employeeCreateDto.UserName,
};
}
服務:
public async Task<Employee> Post(EmployeeCreateDto employeeCreateDto)
{
var mapper = new EntityMapper();
var employee = mapper.FromEmployeeCreateDtoToEmployee(employeeCreateDto);
try
{
await _unitOfWork.EmployeeRepository.Insert(employee);
await _unitOfWork.SaveChangesAsync();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
try
{
ApplicationUser user = new ApplicationUser()
{
UserName = employee.UserName,
PasswordHash = employee.Password
};
IdentityResult result = await _userManager.CreateAsync(user, employee.ConfirmPassword);
if (result.Succeeded)
{
Task<IdentityResult> roleResult;
//Check that there is an Employee role and create if not
Task<bool> hasEmployeeRole = _roleManager.RoleExistsAsync(UserRoles.Employee);
hasEmployeeRole.Wait();
if (!hasEmployeeRole.Result)
{
ApplicationRole roleCreate = new ApplicationRole();
roleCreate.Name = UserRoles.Employee;
roleResult = _roleManager.CreateAsync(roleCreate);
roleResult.Wait();
}
Task<IdentityResult> newUserRole = _userManager.AddToRoleAsync(user, UserRoles.Employee);
newUserRole.Wait();
try
{
//Commit the transaction
await _context.SaveChangesAsync();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return employee;
}
員工 Model 有一個名為 UserId 的字段,該字段與 ApplicationUser 的 Id 不同。 插入后立即:
應用用戶用戶 = 新應用用戶()
我想打電話給:
等待_unitOfWork.EmployeeRepository.Insert(雇員);
並使用來自 ApplicationUser 的 Id 更新 Employee Model UserId。
我如何實現這一目標?
謝謝
您是否嘗試如下訪問它;
try
{
await _unitOfWork.EmployeeRepository.Insert(employee);
await _unitOfWork.SaveChangesAsync();
var employeeId = employee.id;
}
很抱歉,我刪除了那篇文章。 我希望您可以通過以下方式獲取應用程序用戶 ID,然后更新 Employee。
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var user = new ApplicationUser() { "Pass your Application user parameters"};
var result = manager.Create(user, "Your Password");
if (result.Succeeded)
{
string newId = user.Id;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.