6

I have a JSON string and I am deserlizing it into a EF entitiy.

Report result = js.Deserialize<Report>(json);

I am trying to update the entity in my context with the same ID to have the values of my deserlized one.

var reportToUpdate    _entities.Reports.Single(x => x.Id == result.Id)

I want to do something like this

reportToUpdate = set all values to the values from result
context.SaveChanges();

How can I do this?

I would like to avoid doing something like this:

report.param1 = result.param1
report.param3 = result.param3
report.param3 = result.param3

because there are about 50 properties on this entity.

0

2 Answers 2

9

This should work for you.

context.Reports.Entry(reportToUpdate).CurrentValues.SetValues(result);
context.SaveChanges();

Be aware that SetValues does not follow navigational properties or related objects, only complex/simple properties of the entity itself.

Sign up to request clarification or add additional context in comments.

2 Comments

With this method be sure to set the Key/Id of 'result' to that of 'reportToUpdate'. if 'result' has an Id=0 then it will throw an exception.
shouldn't that be context.Entry(reportToUpdate).CurrentValues.SetValues(result); That is contexts track the entry's, not the DBSets
1

If you already populated the entity model, then you just need to do attach the entity

Try something like this.

_context.Reports.Attach(result);
_context.Entry(result).State= EntityState.Modified;

follow this link for more details.

1 Comment

I tried this and I get an error that it already has one with the same ID. This 'new' one deserialized from json was an 'edit' to one already in the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.