有什么区别呢.AsNoTracking()做什么呢? [英] What difference does .AsNoTracking() make?

查看:433
本文介绍了有什么区别呢.AsNoTracking()做什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于 .AsNoTracking()扩展的问题,因为这是所有相当新的,相当混乱。

I have a question regarding the .AsNoTracking() extension, as this is all quite new and quite confusing.

我使用的是每个请求的上下文一个网站。

I'm using a per-request context for a website.

我的许多实体不会改变,因此不必进行跟踪,但我有下面的场景,我不能确定发生了什么事情到数据库,甚至它是否使在这种情况下的差异。

A lot of my entities don't change so don't need to be tracked, but I have the following scenario where I'm unsure of what's going to the database, or even whether it makes a difference in this case.

这个例子是我目前做的:

This example is what I'm currently doing:

context.Set<User>().AsNoTracking()
// Step 1) Get user
context.Set<User>()
// Step 2) Update user

这是与上述相同,但去掉 .AsNoTracking()步骤1:

This is the same as above but removing the .AsNoTracking() from Step 1:

context.Set<User>();
// Step 1) Get user
context.Set<User>()
// Step 2) Update user

步骤1和; 2使用相同的背景,但出现在不同的时间。我想不通,在于是否有任何区别。作为第二步是更新我猜测双方将访问数据库的两倍呢。

The Steps 1 & 2 use the same context but occur at different times. What I can't work out is whether there is any difference. As Step 2 is an update I'm guessing both will hit the database twice anyway.

谁能告诉我有什么区别?

Can anyone tell me what the difference is?

推荐答案

不同的是,在第一种情况下检索用户不受背景下,所以当你要保存用户返回到数据库,则必须将其附加追踪并设置在用户的正常状态,从而使EF知道它应该更新现有的用户,而不是在插入一个新的。在第二种情况下,你不需要做,如果您加载和保存用户使用相同的上下文实例,因为跟踪机制处理,对你。

The difference is that in the first case the retrieved user is not tracked by the context so when you are going to save the user back to database you must attach it and set correctly state of the user so that EF knows that it should update existing user instead of inserting a new one. In the second case you don't need to do that if you load and save the user with the same context instance because the tracking mechanism handles that for you.

这篇关于有什么区别呢.AsNoTracking()做什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆