cost
cost

Reputation: 4490

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

Upvotes: 3

Views: 632

Answers (1)

cost
cost

Reputation: 4490

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;

Upvotes: 2

Related Questions