简体   繁体   English

实体框架变更跟踪(只读)查询

[英]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). 我的情况是,我们有一个运行状况检查例程,该例程每10秒对一个表进行一次选择,并且很少需要更新(仅在部署了新版本时才更新记录)。 So should we do the health check with change tracking turned off turned on? 那么我们应该在关闭变更跟踪功能的情况下进行健康检查吗?

According to your use case, I think No-tracking queries will give big performance boost to your app. 根据您的用例,我认为No-tracking查询将big performance boost您的应用程序的big performance boost

So you can do that using AsNoTracking() 因此,您可以使用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. 如果您知道数据库中already exists一个entity ,但是context not currently being tracked ,则可以使用DbSet上的Attach方法告诉context跟踪该实体,如下所示。

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 参考: 实体状态和SaveChanges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM