Reputation: 573
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 it may be being assigned a temporary value rather than using the existing one.
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; }
}
Upvotes: 1
Views: 268
Reputation: 58
What I suspect is happening is that the Id property doesn't have a corresponding field on the form.
I'm not totally up-to-date on how Razor pages work (that is what you're using, right?)
However, I suspect that when GET
ting the page, the LoadTable property is set and its properties are used inside a view, in order to fill out the form with the current values.
Then when the form is submitted, the framework creates a new instance of the LoadTable
class, then it grabs the values from the request and sets the corresponding properties in the (new) instance of LoadTable
.
But since there's no ID field on the form, it cannot set the ID property and that's why it just has the default value.
If my guess is correct, then the solution is to add a new field (you can make it hidden if you want) to the form and set the value to the ID of the LoadTable.
Upvotes: 2