razor pages EF 6.0 insert data

Curious Cat 21 Reputation points
2022-10-11T10:08:41.333+00:00

While adding data to the database,

Some people insert data directly this way :

...
ApplicationDbContext.Add(MyModel);
await ApplicationDbContext.SaveChangesAsync();
...

And some peoplpe add line by line the table field names :

...
a_field = class_file.incoming_form_value
b_field = class_file.incoming_form_value
c_field = class_file.incoming_form_value
...
....SaveChangesAsync();

Whats the different (logic) here ? Both do the same.
Plus, I noticed also that both ways can have Nullable fields in the DB table.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,202 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,141 Reputation points
    2022-10-11T12:49:55.973+00:00

    The first approach with the .Add() is used when the entity model is disconnected (not tracked) from the DbContext and needs to be added to the DbContext before it can be saved. This is a common pattern in web development.

    The second method is used when the DbContext was queried to fill the entity. Therefore the entity is being tracked. SaveChangesAsync() saves all entities that have changes.

    Please see the Entity Framework 6.0 official documentation.

    Change Tracking in EF Core
    Working with Nullable Reference Types

    0 comments No comments

0 additional answers

Sort by: Most helpful