DbContext - 如何在我更新数据库时阻止我的数据库创建新记录?
DbContext - how do I stop my database from creating new records when I'm updating them?
我的数据库在应该更新当前记录时不断创建新记录。 Razor-Pages 项目,asp.net 2.2.
应该发生什么:
- 正在从 asp.net 身份用户 class
中检索电子邮件
- 通过比较电子邮件在 table 个公司中找到匹配 == 电子邮件
- 更新记录
- 正在保存更改
它不是更新,而是创建新记录。
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var email = await _userManager.GetEmailAsync(user);
var company = _context.Companies.FirstOrDefault(b => b.Email == email);
Firma = user.Firma;
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var email = await _userManager.GetEmailAsync(user);
var company = _context.Companies.First(a => a.Email == email);
company.Navn = Input.Firma;
company.Postnr = Input.Postnr;
company.Sted = Input.Sted;
company.Beskrivelse = Input.Beskrivelse;
_context.SaveChanges();
return RedirectToPage();
}
_context.Companies.Update(company);
_context.SaveChanges();
我的数据库在应该更新当前记录时不断创建新记录。 Razor-Pages 项目,asp.net 2.2.
应该发生什么:
- 正在从 asp.net 身份用户 class 中检索电子邮件
- 通过比较电子邮件在 table 个公司中找到匹配 == 电子邮件
- 更新记录
- 正在保存更改
它不是更新,而是创建新记录。
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var email = await _userManager.GetEmailAsync(user);
var company = _context.Companies.FirstOrDefault(b => b.Email == email);
Firma = user.Firma;
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var email = await _userManager.GetEmailAsync(user);
var company = _context.Companies.First(a => a.Email == email);
company.Navn = Input.Firma;
company.Postnr = Input.Postnr;
company.Sted = Input.Sted;
company.Beskrivelse = Input.Beskrivelse;
_context.SaveChanges();
return RedirectToPage();
}
_context.Companies.Update(company);
_context.SaveChanges();