You can define the relationship using the fluent API.
modelBuilder.Entity<Pet>
.hasOptional(p => p.Owner)
.willCascadeOnDelete(false);
This will configure the relational property as optional, and will ensure that cascade delete does not take effect. You can create a Pet
without an Owner
, and deleting an Owner
will not delete the associated Pets
.
However you cannot assign Pet.OwnerId
to an OwnerId
that doesn't exist in the Owner
table. If you truly need to have some way of tracking invalid OwnerId
values, you either need to have a separate property which you manually update with an arbitrary value, or you would need to define these objects without using a navigation property, and perform your lookups manually.
It would be an exceptional situation where you would need to supply an arbitrary value for OwnerId
that doesn't match the Owner
table; In 99% of all cases, an optional relationship which accepts a valid OwnerId
or null
is all that is necessary.
The OwnerId
property isn't actually necessary on the Pet
object, but if it is present, it should be set to int?
to be nullable.