Reputation: 221
Entities
Person
INT Id
Address Adresss
Address
INT Id
INT PersonId
Model Builder
modelBuilder.Entity<Person>()
.HasOne(p => p.Address)
.WithOne()
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey<Adresss>(a => a.PersonId)
.IsRequired();
When Id do this
Person.Address = null
and then save changes. I get this error
The association between entity types 'Person' and 'Address' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable.
I think the error is telling me to make PersonId
(the foreign key) optional. So like below. Which is will result in the foreign key column being nullable in the SQL Server database.
What I want is to allow for a user to delete an Address but if an address is added then it must contain a PersonId. So I don't want this to be null
Address
INT Id
INT? PersonId
Can make I make personId in the address table not null but also allow person's address property to be optional? in other words one to one OR one to zero relationship
Upvotes: 1
Views: 196
Reputation: 164
I think that the best way to null Address is this:
Context.Address.Remove(Person.Address)
because Address is a DbSet, not only a navigation property. You have to mark the entity "Address" to be removed.
Upvotes: 1