Reputation: 614
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.
There is a [Required]
Data Annotation on Question in the Answer entity which seems to be causing the problem.
Upvotes: 1
Views: 51
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:
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.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