As the context ( DbContext
) works when I call an entity by First()
, FirstOrDefault()
, Find(value)
, ie I bring a record to change:
Model:
[Table("Credit")]
public class Credit
{
public Credit()
{
}
public Credit(string description)
{
Description = description;
}
public Credit(int id, string description)
{
Id = id;
Description = description;
}
[Key()]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required()]
[MaxLength(50)]
public string Description { get; set; }
public bool Status { get; set; }
public int Lines { get; set; }
}
Context (DbContext):
public class Database : DbContext
{
public Database()
:base(@"Server=.\SqlExpress;Database=dbtest;User Id=sa;Password=senha;")
{
Database.Initialize(false);
}
public DbSet<Credit> Credit { get; set; }
}
Running operations:
class Program
{
static void Main(string[] args)
{
using (Database db = new Database())
{
db.Database.Log = ca => WriteLog(ca);
int value = 1;
Credit cr = db.Credit.Find(value);
cr.Lines = cr.Lines + 1;
db.SaveChanges();
}
System.Console.WriteLine("Pression <Enter> ...");
}
public static void WriteLog(string c)
{
System.Console.WriteLine(c);
}
}
In the code above, basic auditing is used, which shows which SQL
is being generated, in the example case two are Select
and Update
, being an update only of what was modified, as shown in debug
logo below:
Then,concludethattheupdate
ismadeonlyofthepropertythathasbeenchanged.
1-DoesContexthavesomewaytogeneratethesamesyntax?
Yesitgeneratesthesamesyntax,makingupdatesonlyofpropertiesthathavebeenchanged.
2-Isthereanywaytoseethequerybeingsenttothebankinthiscase?
Yes,itdoes,db.Database.Log
willbringtheSQL
generatedbythecontext.
using(Databasedb=newDatabase()){db.Database.Log=ca=>WriteLog(ca);
CanalsobeusedintheDebugTrace
window:
db.Database.Log=ca=>System.Diagnostics.Debug.WriteLine(ca);
3-HowisContextmadeawarethatonlytheNamecolumnhaschanged?
Creditcr=db.Credit.Find(value);cr.Lines=cr.Lines+1;db.Entry(cr).Property(x=>x.Lines).IsModified
Thisshowsdb.Entry(cr).Property(x=>x.Lines).IsModified
ifthepropertyhaschanged,theContextisbasedonthetrueresponse(true
),andthecodeonlychangeswhatismodifiedastrue
.
Thereisnothingimplementedtocheckwhichfieldsaremodifiedatonce,butcanbeeasilydonebyanextensionmethod,totellwhichfieldshavechangedandwhichhavenot.
publicstaticclassMethodsUpdate{publicstaticDictionary<string,bool>GetUpdatePropertyNames<T>(thisDbEntityEntry<T>entry)whereT:class,new(){Dictionary<string,bool>entryUpdate=newDictionary<string,bool>();foreach(stringnameinentry.CurrentValues.PropertyNames){entryUpdate.Add(name,entry.Property(name).IsModified);}returnentryUpdate;}}Dictionary<string,bool>propertyChanges=db.Entry(cr).GetUpdatePropertyNames();
Inthisspecificcasethechangeinthebankhasnotyetbeenapplied,onlyinitscontext.
References: