Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Change Tracking (Read Only) query

Just wanted peoples opinions on a scenario:

Would it be more efficient to:

  1. Select a record with change tracking turned off and then if it needs to be updated reattach the object to the context for update?
    • or -
  2. Select a record with change tracking turned on just in case the record needs to be updated?

Or is this trivial?

My scenario is that we have a health check routine that does a select on a table every 10 seconds and very rarely needs to be updated (Only updates the record if a new version has been deployed). So should we do the health check with change tracking turned off turned on?

like image 545
Brendan Avatar asked Nov 01 '25 04:11

Brendan


1 Answers

According to your use case, I think No-tracking queries will give big performance boost to your app.

So you can do that using AsNoTracking()

using (var context = new HelthContext())
{
    var patients = context.Patients.AsNoTracking().ToList();
}

If you have an entity that you know already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet as shown below.

var existingPatient = new Patient { Id = 1, Name = "Patient 1" }; 

using (var context = new HelthContext()) 
{ 
    context.Patients.Attach(existingPatient ); 

    // Do some more work...  

    context.SaveChanges(); 
}

Reference : Entity states and SaveChanges

like image 80
Sampath Avatar answered Nov 02 '25 19:11

Sampath