Reputation: 7194
I have an entity that has a nullable int which is a one-to-one foreign key to itself. Simplified, this is the entity:
public class Step
{
public int StepId { get; set; }
public string Foo { get; set; }
public int? RelatedStepId { get; set; }
[ForeignKey("RelatedStepId")]
public Step RelatedStep { get; set; }
}
This works fine - I'm able to set the RelatedStepId
to the value of another record's StepId
. However, there are times when I need to break this relationship. If I set RelatedStepId
to null
and then save changes, the field retains its previous value. I have verified that the RelatedStepId
truly is null
, but when I log the SQL being generated (using .EnableSensitiveDataLogging() so I can see the values) I can see that it is passing the previous value in the SQL, not null
.
I feel like I must be missing something simple, but I've been searching and searching and so far I haven't found anything that relates to this specific issue. How do I get EF Core to actually send null
as the value for RelatedStepId
?
Upvotes: 2
Views: 1332
Reputation: 4461
You shoud set RelatedStep
to null too. I guess you didn't clear this object.
Filling one of RelatedStepId
or RelatedStep
is enough for EF
to save the value and if you don't want it, you have to clear both of them.
Upvotes: 2