In ms docs Razor pages tutorial the DbContext has a DbSet Students set
public class SchoolContext : DbContext { public DbSet<Student> Students { get; set; }
and in the OnPostAsync() method creates and then adds updated students using DbSet<TEntity>.Add(TEntity)
method(documentation):
var emptyStudent = new Student(); if (await TryUpdateModelAsync<Student>( emptyStudent, "student", // Prefix for form value. s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)) { _context.Students.Add(emptyStudent); await _context.SaveChangesAsync();
The MVC tutorial also has a DbContext
that has a DbSet Students however in the StudentsController.cs Create() post method, it adds students directly calling DbContext.add() on the DbContext:
_context.Add(student); await _context.SaveChangesAsync();
The only other difference I see is that in MVC the student was passed in as a parameter:
public async Task<IActionResult> Create([Bind("LastName,FirstMidName,EnrollmentDate")] Student student) {
Is there any difference between the two? Can they be used interchangeably. When to use one or the other?
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. Has code to configure each DbSet where TEntity is a model e.g. Blog, Post.
Methods. Add(TEntity) Adds the given entity to the context underlying the set in the Added state such that it will be inserted into the database when SaveChanges is called.
The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.
In the sources you can find out the implementation of InternalDbSet
's (which is a concrete implementation of the abstract DbSet
) Add
method:
public override EntityEntry<TEntity> Add(TEntity entity) => _context.Add(entity);
which clearly means that it's just a facade over DbContext
s Add
.
Technically this means that both do exactly the same.
The source now looks a bit different from Wiktor's answer, but the docs provide this statement:
Many methods, including
Add
,Update
,Attach
, andRemove
, have implementations on both DbSet and DbContext. These methods have exactly the same behavior for normal entity types....
The exception to this rule is when using shared-type entity types, which were introduced in EF Core 5.0, primarily for many-to-many join entities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With