1 year ago

#113208

test-img

bpoxy

EF Core 6: Optional HasOne Relationship

I have a situation similar to Entity Framework 6 define a REALLY optional foreign key in which I would like to configure a HasOne relationship when the foreign key may or may not exist in the target table. At the time when that question was asked, it seems the solution was to use HasOptional. However, HasOptional has since been removed from EF in favor of implicit required/optional determination based on whether the foreign key property is nullable. This works great for the typical optional relationship scenario but it does not allow for handling of my case.

Currently, querying a record in which the foreign key doesn't exist in the target table via SingleOrDefaultAsync returns null so obviously EF is not happy with the foreign key being present but "invalid".

I realize having a foreign key that might not exist in the target table is not a great data model but, unfortunately, I cannot change this. I'm thinking this isn't a supported use case but wanted to ask here before I resorted to manual lookups or joins.

Thanks in advance.

entity-framework

foreign-keys

option-type

has-one

0 Answers

Your Answer

Accepted video resources