What is the difference between DbContext.Add () and DbContext.DbSet <TEntity> .Add (TEntity)? When do you use one against the other?
In the ms docs of the Razor page , in DbContext there are DbSet students installed
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
and in the OnPostAsync () method creates and then adds updated students using the method DbSet<TEntity>.Add(TEntity)
(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 hasDbContext
one that has DbSet students, but in the StudentsController.cs Create () post, it adds to students directly calling DbContext.add () in DbContext:
_context.Add(student);
await _context.SaveChangesAsync();
The only difference I see is that in MVC the student was passed as a parameter:
public async Task<IActionResult> Create([Bind("LastName,FirstMidName,EnrollmentDate")] Student student)
{
Is there a difference between the two? Can they be used interchangeably. When to use this or that?
+4
1
InternalDbSet
( DbSet
) Add
:
public override EntityEntry<TEntity> Add(TEntity entity)
=> _context.Add(entity);
, DbContext
Add
.
, .
+3