Entity Framework Core autosaves objects in Blazor

blazor blazor-client-side entity-framework-core sql-server


I might be not getting how some stuff work in Blazor, but here's what my issue is:

whenever I want to edit an object for example People object, I select it in @page "/people" from a table, then I'm redirected to the @page "people/edit/id". In @page "people/edit" I have an EditForm with InputText corresponding to the people model and the @bind value, everything is normal, it loads the data correctly.

The problem is when I edit some of the inputs and not save the data, just modify its values, and then go back to the @page "people", or anywhere, the object is modified.

I even put a breakpoint to watch the object being pulled from the database through Entity Framework Core, and it shows the modified version too, but checking on the database table, it does not seem to be affected.

It sounds impossible, but I tried with brand new projects, or others people projects in video tutorials, try replicating and does the same thing, so what's the deal here?

@page "/People/edit{id}"

@code {
    [Parameter] public string id { get; set; }
    Person person = new Person();

    protected override async Task OnParametersSetAsync()
        person = await PersonService.GetByIdAsync(id);
4/2/2020 8:28:31 PM

Accepted Answer

Firstly, if you put some object as a model for an EditForm and make some changes to it, all changes are reflected in the object immediately, but not after you click a submit. Secondly, when you pull an object from a database it gets attached to the DbContext and stays attached, unless you detach it explicitly. When you query the entity, already attached to the context, the context does not query the database again, but gives you the attached entity. And if you have made some changes to it, you get these changes. But those changes are not saved to database until you execute context.SaveChanges, so when you see the actual database, you see the unchanged data.

The difference with Net Core MVC is that Net Core MVC is stateless. Though you use references to the .NET objects in .cshtml files, they are used only during one query and get destroyed after the response is sent to client. When you use Blazor, you get actual .NET runtime ether on server (Blazor server) or on client (Blazor wasm), so your objects remain and preserve their state.

4/13/2020 8:59:39 PM

Related Questions


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