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

查看:46
本文介绍了.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

这与上面相同,但从第 1 步中删除了 .AsNoTracking():

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 使用相同的上下文但发生在不同的时间.我无法弄清楚是否有任何区别.由于第 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天全站免登陆