3

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. 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.

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. 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? 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). 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.

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?

Community
  • 1
  • 1
cost
  • 4,420
  • 8
  • 48
  • 80
  • Have you tried setting the entity's state to `Modified` in the context? – Asad Saeeduddin May 26 '14 at 03:34
  • In addition to comment of @Asad: http://stackoverflow.com/a/20451793/1803777 – Ulugbek Umirov May 26 '14 at 03:44
  • @Asad Looking at it in the debugger, I see that it attaches as `Unchanged` and then after I set Deleted to true, it becomes `Modified`, just like it should. It still seems to want to validate the unchanged fields though – cost May 26 '14 at 03:58
  • @UlugbekUmirov That link has a lot of great info, but it didn't help me. I even tried setting the entire thing to `Unchanged` and then individually setting the Deleted property to `Modified` but I still got the same error – cost May 26 '14 at 04:02

1 Answers1

2

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.

Check out this question for an explanation of it, but essentially what I needed was

SHEntity.Configuration.ValidateOnSaveEnabled = false;
Community
  • 1
  • 1
cost
  • 4,420
  • 8
  • 48
  • 80