.net Core 2.2 EF: SaveChangesAsync() setting unrelated columns to null

asp.net-core c# entity-framework-core

Question

I have an Asp.Net Core 2.2 application. I've written a couple of new Razor pages to update some new data to an existing model.

The problem is that when I "submit" my form and call SaveChangesAsync(), it updates the fields I've changed ... and it ERASES most of the other fields in the record.

The model has 40 or 50 properties; I'm only trying to update 3 or 4 of them.

But EVERYTHING except "ID" and the fields in my form are getting set to "null" by the update.

Q: Any idea what I'm missing?

public class EditPageModel : PageModel
{
    private readonly Project.Models.MyContext _context;

    [BindProperty]
    public MyModel MyRecord { get; set; }

    public EditPageModel(Project.Models.MyContext context)
    {
        _context = context;
        // <= This is OK...

    public async Task<IActionResult> OnGetAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        MyRecord = await _context.MyModel.FirstOrDefaultAsync(m => m.ID == id);
        // <= This is OK, too: I call "return Page()" and everything looks fine...

    public async Task<IActionResult>OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        // Update DB
        _context.Attach(MyRecord).State = EntityState.Modified;
        try
        {
            await _context.SaveChangesAsync();  
        }
        catch (DbUpdateConcurrencyException)
        {
            // No exceptions, no errors or warnings: Never get here...
            ...
        }
        return RedirectToPage("./Index");
1
4
3/3/2020 1:28:08 AM

Accepted Answer

You have two options:

Option 1: add hidden fields for each and every property in your model that don't need to be changed.

Option 2: load record from database, map properties from model to the db object and save changes, without attaching the binding model to the context.

4
3/3/2020 1:36:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow