C# Attach() 在实体框架中究竟做了什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11709266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What exactly does Attach() do in Entity Framework?
提问by John Mitchell
Possible Duplicate:
Entity Framework 4 - AddObject vs Attach
可能的重复:
实体框架 4 - AddObject 与附加
I've seen the use of attach a few times, especially when manipulating models.
我见过几次使用 attach ,尤其是在操作模型时。
using (var context = new MyEntities())
{
context.Attach(client);
context.SaveChanges();
}
From the context it looks like it just runs an UPDATEagainst a record in EntityFrameworks, but I also see it used in DELETEstatements. So I can only assume it just gets a pointer to the database?
从上下文来看,它似乎只是UPDATE针对 EntityFrameworks 中的记录运行,但我也看到它在DELETE语句中使用。所以我只能假设它只是得到一个指向数据库的指针?
Could someone point me in the right direction, I've googled it for a while and whilst I don't come up empty, I can't find any good explinations of what it does (from an overview, and internally).
有人能指出我正确的方向吗,我已经用谷歌搜索了一段时间,虽然我没有找到空洞,但我找不到任何关于它做什么的好解释(从概述和内部)。
采纳答案by Not loved
Just as a point of interest the code you have posted does nothing
作为一个兴趣点,您发布的代码什么也不做
using (var context = new MyEntities())
{
context.Attach(client);
context.SaveChanges();
}
All this does is attach the entity to the tracking graph make no modifications to the entity and save it.
所有这些都是将实体附加到跟踪图上,不对实体进行修改并保存它。
Any changes made to the object before attach are ignored in the save
在附加之前对对象所做的任何更改在保存中都将被忽略
What would be more interesting is if it actually updated a property ie:
更有趣的是它是否真的更新了一个属性,即:
using (var context = new MyEntities())
{
context.Attach(client);
client.Name = "Bob";
context.SaveChanges();
}

