TomJerrum
TomJerrum

Reputation: 614

Updating Entity Framework entity is failing because of relational Entity

I have this structure.

Question ---< Answer
--------      ------
Id            Id
Text          Value

I am attempting to update the value of Answer by getting it by Id from the DbContext setting the value to something new and then calling SaveChanges.

This is failing stating that question is required. I have the navigational property on Answer virtual.

For some reason EF thinks that I want the question to be null. If I set a breakpoint and lazy load the question in then it all works fine.

I only want to update the value, will I need to eager load the question? If so this seems odd to me.

Addendum

There is a [Required] Data Annotation on Question in the Answer entity which seems to be causing the problem.

Upvotes: 1

Views: 51

Answers (1)

Aleksa
Aleksa

Reputation: 3104

Yea, that's how it works. If your navigation property is not nullable, save will fail until you load it. You have 2 solutions:

  1. If you have navigation property virtual Question Question { get; set; } you should also add int QuestionID { get; set; } so when you load your Answer you will have QuestionID value set, and it means your Question can be null, because QuestionID information is enough.
  2. If you don't have context.Entry(entityToUpdate).State = EntityState.Modified; and have context.Configuration.AutoDetectChangesEnabled = true; then when you change something on Answer the save changes will only update changed values, not the other ones, so the null property wont be a problem.

Upvotes: 2

Related Questions