I'm watching some tutorial programming about asp.net core
In some tutorial lecturers use this code for update data in database
DataContext db = new DataContext();
var query = db.TblUsers.where(x => x.Id == 3).single();
query.Name = "Sami";
db.TblUsers.Attach(query);
db.Entry(query).state = EntityState.Modified;
db.SaveChanges();
But some lecturers use this code for updating data in database
DataContext db = new DataContext();
var query = db.TblUsers.where(x => x.Id == 3).single();
query.Name = "Sami";
db.Update(query);
db.SaveChanges();
In fact I'm confuse to use which of them? Because both code working.
Please tell me what is exactly different between those codes ?
For your current code, there is no need to use Attach
for the first way. If you want to update Model by retriving record from database, kindly go with second way which is much convenience.
For Attach
, it will put entity in the graph into the Unchanged state, and set entity as Modified
by db.Entry(query).state = EntityState.Modified
, then the changes in query
will be saved to database. Since db.TblUsers.where(x => x.Id == 3).single()
is already tracking the query
, there is no need to use Attach
.
There are two types for query, tracking
and no-tracking
. If you did not specificy the query as no-tracking
expecitly like db.TblUsers.AsNoTracking().where(x => x.Id == 3).single()
, the entity will be tracking which is Unchanged
state.
For db.Update(query);
, it will begins tracking the given entity in the EntityState.Modified
state such that it will be updated in the database when Microsoft.EntityFrameworkCore.DbContext.SaveChanges is called.