2

I'm surprised that despite spending quite some time looking for the answer I haven't found it on the internet myself. What's even more surprising to me is that people tend to compare Attach to Add, and not to the Update. Furthermore, I've found very little mentions of the actual Update method, despite it being seemingly most obvious choice for the desired modify operation.

From the materials I managed to find I figured, that Attach should be used when you know the object exists somewhere in the database. If you don't make changes to it, no operations will be performed on the entity, and if you do - it will be updated. But then why would you need Update if it does the same thing from the sound of it?

I have this code snippet which I took from udemy course.

MovieController.cs

[HttpPut("{id}")]
        public IActionResult ReplaceMovie(long id, [FromBody] Movie m)
        {
            if (ModelState.IsValid)
            {   
               ////
               // logic in question starts here vvv
               ////
                m.MovieId = id;
                if (m.Studio != null && m.Studio.StudioId != 0)
                {
                    context.Attach(m.Studio);
                }
                context.Update(m);
                context.SaveChanges();
                return Ok();
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

But then why not just make it this way?

m.MovieId = id;
context.Update(m);
context.SaveChanges();
return Ok();

Would it not result in the same outcome, since we know that in case the Movie already has it's Studio assigned, then it (the Studio) exists in the database and we don't need to apply any changes to it?

Now if we applied some changes to the movie AND to the studio objects, then wouldn't it be safer to just perform the update modifications in their individual controllers? For example - if I want to update the movie and the studio, then I would first call the StudioController which would perform the modify operation on the Studio and then call the MovieController to update the movie.

What approach would be optimal for the best flexibility and clarity? What should I know about Attach and Update in general?

kzmijak
  • 77
  • 6
  • 1
    https://stackoverflow.com/questions/41025338/why-use-attach-for-update-entity-framework-6 – Ben Mar 05 '20 at 13:18
  • Does this answer your question? [Why use Attach for update Entity Framework 6?](https://stackoverflow.com/questions/41025338/why-use-attach-for-update-entity-framework-6) – phuzi Mar 05 '20 at 13:33
  • No, it doesn't relate to questions I asked for the most part – kzmijak Mar 05 '20 at 13:34
  • If you check one of the official tutorials, eg for [Razor Pages](https://learn.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/da1?view=aspnetcore-3.1) or [MVC](https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/controller-methods-views?view=aspnetcore-3.1#processing-the-post-request) you'll see there's no call to `Attach` in the `Edit` page or action. Just setting the object to the `Modified` state, the same thing that `Update` does – Panagiotis Kanavos Mar 05 '20 at 13:54
  • That code is so unusual that I googled parts of it and found ... [an exact copy](https://github.com/PacktPublishing/Hands-on-Web-Development-with-ASP.NET-Core-and-Angular-7/blob/master/Section%202/ex%202.7/Controllers/MovieController.cs). I thought Packt sells its own courses directly .... weird, and not just the *unnecessary* calls to `Attach` right before the calls to `Add` or `Update`. May I suggest you start with the *official and free* tutorials and courses? This way you know where your personal details end up (if they're ever needed). – Panagiotis Kanavos Mar 05 '20 at 14:00
  • I'd also suggest looking into the free [Visual Studio Dev Essentials](https://visualstudio.microsoft.com/dev-essentials/) program. As part of the tools, it offers 1 month of free access to Pluralsight's courses. Those courses are created by some of the *best* speakers and authors. They are the ones that get "borrowed" by less scrupulous sites – Panagiotis Kanavos Mar 05 '20 at 14:04
  • I took the code from the course I bought on Udemy, so yes, it's not mine and that's why I was so intrigued byit, because the original author just gave the code to copy and pushed forward with the lesson without any explanation of what is going on. – kzmijak Mar 05 '20 at 15:31

1 Answers1

4

.Update will mark the entity as being in a Modified state. Update can be used to start tracking a mix of new and existing entities where the existing entities may have some modifications. The new entities will be inserted while the existing entities will be updated.

.Attach will mark the entity as being in an Unchanged state. However, entities will be put in the Added state if they have store-generated keys (e.g. Identity column) and no key value has been set. This means that when exclusively using store-generated keys, Attach can be used to start tracking a mix of new and existing entities where the existing entities have not changed. The new entities will be inserted while the existing entities will not be saved other than to update any necessary FK values.

Source Info:

Why use Attach for update Entity Framework 6?

https://blog.oneunicorn.com/2016/11/17/add-attach-update-and-remove-methods-in-ef-core-1-1/

Ben
  • 1,820
  • 2
  • 14
  • 25
  • I believe I understand now. The name "Attach" seems very counter-intuitive for me, since it doesn't actually describe what's happening behind the scenes. – kzmijak Mar 05 '20 at 15:56