简体   繁体   English

在没有往返的情况下更新实体框架6

[英]Update in Entity Framework 6 without a roundtrip

In EF 4.1, when I wanted to update a record, I could avoid the roundtrip of loading it first by creating a new entity, setting the primary key, attaching it to the DBContext, then updating the field. 在EF 4.1中,当我想更新记录时,我可以通过创建新实体,设置主键,将其附加到DBContext,然后更新字段来避免首先加载它。 Change tracking would ensure that only the fields I changed after attaching the entity would update. 更改跟踪将确保只有在附加实体后我更改的字段才会更新。 This method is explained here . 这里解释这种方法。 But now I'm trying it with EF 6.1 on an ASP.NET project, and find that it doesn't work. 但现在我正在使用EF 6.1在ASP.NET项目上尝试它,并发现它不起作用。

var court_code = new System_Court();
court_code.UID = UID;
SHEntity.System_Court.Attach(court_code);
court_code.Deleted = true;
SHEntity.SaveChanges();

This would have worked previously, but now it gives me a validation error, saying I'm missing various required fields - which I am, but it shouldn't care since Deleted is the only record I want updated. 这可能以前有用,但现在它给了我一个验证错误,说我缺少各种必填字段 - 我是,但它不应该在意,因为Deleted是我想要更新的唯一记录。 But if I do it with a roundtrip, it works fine. 但如果我通过往返进行,它可以正常工作。

var court_code = SHEntity.System_Court.Where(w => w.UID == UID).First(); 
court_code.Deleted = true;
SHEntity.SaveChanges();

Is this something that has changed between EF 4 and EF 6? 这是EF 4和EF 6之间的变化吗? I see that EF 6 generates different looking entity classes than EF 4 did (EF 4 had a bunch of stuff like Entity Key, where as EF 6 looks like a simple POCO). 我看到EF 6生成了与EF 4不同的实体类(EF 4有一堆像Entity Key这样的东西,其中EF 6看起来像一个简单的POCO)。 Googling shows a number of changes between EF 4 and 5, but I don't see any mention about how to make this trick work now. 谷歌搜索显示了EF 4和5之间的一些变化,但我没有看到任何提及如何使这个技巧现在工作。

Update: Looking at the sql executed by the second block of code, I see that just Deleted is being updated, as it should.. so is this some issue with creating the object and attaching it like that? 更新:看看由第二个代码块执行的sql,我看到只是Deleted正在更新,因为它应该..所以这是创建对象并附加它的一些问题?

While coding I managed to stumble around the correct answer a few times before finally realizing that I was asking the wrong question. 虽然编码我设法偶然发现了几次正确的答案,然后才意识到我在问错了问题。 With the help of the comments, I learned about some EF 5 breaking changes involving change tracking, and that helped me realize that it was validation that I needed to disable. 在评论的帮助下,我了解了一些涉及变更跟踪的EF 5破坏性更改,这帮助我意识到我需要禁用验证。

Check out this question for an explanation of it, but essentially what I needed was 查看这个问题以获得解释,但基本上我需要的是

SHEntity.Configuration.ValidateOnSaveEnabled = false;

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

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