我有一个随机的唯一编号表,它们用作用户的帐户ID。
此方案将在Web API的Register方法中使用,以获取第一个唯一编号并将其附加到用户中,并且在成功创建之后,将从数据库中删除获取的唯一编号:
public async Task<ActionResult> Register([FromBody] RegisterDto model)
{
//get the first unique number from the database
var UniqueNumber = _context.UniqueNumbers.First();
var user = new User
{
UserName = model.Email,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
FirstName = model.FirstName,
LastName = model.LastName,
UserProfile = new UserProfile()
{
AccountNumber = UniqueNumber.Number,
},
};
//creating user
var createResult = await _userManager.CreateAsync(user, model.Password);
if (!createResult.Succeeded) return BadRequest(new { isSucceeded = createResult.Succeeded, errors = createResult.Errors });
//Delete the fetched UniqueId from the database
_context.UniqueNumbers.Remove(UniqueNumber);
_context.SaveChanges();
return Ok(new
{
isSucceeded = true
});
}
我的问题是,如何避免API上的多次调用发生冲突,因为API可能为多次调用返回相同的唯一编号?
答案 0 :(得分:1)
在EF Core和Microsoft SQL Server上,您应仅使用SEQUENCE对象生成密钥。参见Sequences - EF Core
如果真的很想继续进行原始设计,则可以使用FromSql运行DELETE … OUTPUT,例如:
var UniqueNumber = _context.UniqueNumbers.FromSql("delete top (1) from UniqueNumbers output deleted.*").Single();