Edit view not editing the Db entry but instead creating new one
What the title says, when I hit the submit button on the Edit view of my Utilizador model class, it goes to the HTTPPost Edit method in the controller and triggers these lines:
And instead of updating the relevant table row, it simply creates and inserts a new one with the new UserName I passed in through the view.
The commented out code was something I added to try and force it to be the utilizador object I want it to be (for when the update method is called), but when I uncomment and use the code it simply does not add anything.
10 Replies
EF core? EF will decide on update vs create based on the tracking state of the entity
I suspect your edit view is essentially recreating the entire object from scratch, maybe even without the ID, and you then call
update
on it
thats not really how you update entities with EF; the correct way is to fetch the real item and then mutate that object, and call save changes
alternatively, you can set the change tracker state of the entity, but doing that means you are trusting your model binding result a bit too much, imho 🙂 Why is it called Edit, then?
I guess it's my bad for assuming
Okay, what does Update do anyway?
It tries to patch the old object with new object data. It tends to be a bit fucky-wucky depending on whether the PK is there in the new object or not
Prefer either load-edit-save, or
.ExecuteUpdateAsync()
The former being two database calls:
And the latter being one database call
its not?
The view and the method that code was in is called Edit...
Because that's what they're supposed to do. But the EF method is not called
Edit
^
In your snippet there is no reference to any "Edit". I can't comment on anything outside of what you have shared or what EF brings.
In any case, use one of the methods I mentioned instead of
.Update()
and it's 99% sure it'll fix the issue
Unless your controller action is async void
or something
Then you have other issues
@Gipperok, thank y'all again
@ZZZZZZZZZZZZZZZZZZZZZZZZZ it's like the 4th time you've helped me this week
I really appreciate you ❤️
@ZZZZZZZZZZZZZZZZZZZZZZZZZ the clip in your bio did hurt my brain, well done!
Another person experiences the pepeloni lol