4

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?

1

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

same approach i use, but I add this line after attach, context.Entry(existingPatient).State = EntityState.Modified; , I think this is required to tell the context that this data is for update and not insert, right?
that use case is different.that is ,If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. i.e. Attaching an existing but modified entity to the context. @HadiHassan
I have added good Reference above.you too can see that :) @HadiHassan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.