How do I prevent a temporary value being assigned when editing a record with EntityFramework?
I'm struggling with an error I'm getting when trying to update a record. Could anyone offer any input please?
I've created an Edit page for a record, when saving, I get the following error:
The property 'Id' on entity type 'LoadTable' has a temporary value while attempting to change the entity's state to 'Modified'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.
I think Id may be being assigned a temporary value rather than using the existing one but I'm unsure how to prevent this.
From my Edit.cs:
[BindProperty] public LoadTable LoadTable { get; set; } public async Task<IActionResult> OnGetAsync(Guid id) { if (id == null) { return NotFound(); } LoadTable = await _context.LoadTable.FirstOrDefaultAsync(m => m.Id == id); if (LoadTable == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(LoadTable).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!LoadTableExists(LoadTable.Id)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool LoadTableExists(Guid id) { return _context.LoadTable.Any(e => e.Id == id); }
From context:
entity.Property(e => e.Id).HasDefaultValueSql("(newid())");
From Model:
public partial class LoadTable { public Guid Id { get; set; } }
Any help or input would be greatly appreciated. Thanks!
0 comments:
Post a Comment