简体   繁体   中英

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

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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM