Home > Back-end >  Why does my update model operation cause duplicates in ASP.NET Core?
Why does my update model operation cause duplicates in ASP.NET Core?

Time:10-17

I've tried different approaches but my models are being duplicated on every update.

I pass a person object from my view to the controller method via a HTTP POST operation and then call the .Update(...) method.

My view is:

@model Falcon.Models.Person

<h2>User @Model.FullName</h2>
<div>
    <form method="post" class=container>
    <section>
        <h4>General information</h4>
    
    <div class=row>
    <div class=col-25><label asp-for=Surname></label></div>
    <div class=col-75><input asp-for=Surname type="text"/></div>
    </div>  
     <div class=row>
    <div class=col-25><label asp-for=Name></label></div>
    <div class=col-75><input asp-for=Name type="text"/></div>
    </div>  
     ......
    <div class=row> 
        <div class=col-25><label asp-for=Email></label> </div>
        <div class=col-75><input asp-for=Email type="email" /></div>
    </div>         
</section>

<input type="submit" value="Submit changes" asp-action="Edit" asp-controller="Person"/>     
</form>

My PersonController's action is:

 [HttpPost]
    public async Task<IActionResult> Edit (Person person)
    {
        db.Persons.Update(person);
        await db.SaveChangesAsync();           
        return RedirectToAction("Index");
    }

Why are my objects being duplicated on every update operation?

CodePudding user response:

You have to add hidden field for a primary key - Person.Id. Without this entity framework can decide that it is a new object

<input type="hidden" asp-for="Id" />

CodePudding user response:

You're mapping a Person model (@model Falcon.Models.Person) which will be determined unique by a primary key - let's say Person.Id.

Since you're not binding something in your UI to your ID, ASP.NET is generating a new ID every time, meaning it's being recognised as a new person on every "update".

Make it a hidden field so ASP.NET can pass the existing Id value through, and knows it is an update operation & not a creation.

<input type="hidden" asp-for="Id" />
  • Related