Using Entity Framework 6 with the Designer, all our entities have an independent association. So no foreign keys are defined in our model's properties.
Having the following entities with a one-to-many relationship:
public class Parent
{
public Guid Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public Guid Id { get; set; }
public virtual Parent Parent { get; set; }
}
Mapping to the following SQL tables:
CREATE TABLE Parent (
Id uniqueidentifier NOT NULL,
CONSTRAINT PK_Parent PRIMARY KEY CLUSTERED (Id)
)
CREATE TABLE Child (
Id uniqueidentifier NOT NULL,
FkParent uniqueidentifier NOT NULL,
CONSTRAINT PK_Child PRIMARY KEY CLUSTERED (Id)
)
ALTER TABLE Child WITH CHECK
ADD CONSTRAINT FK_Child_Parent FOREIGN KEY(FkParent) REFERENCES Parent ([Id])
ALTER TABLE Child CHECK CONSTRAINT FK_Child_Parent
As you can see we are not using CASCADE ON DELETE
, because my team is against the usage of it.
So the question is, what's the correct way to delete a parent and it's dependent children given only the parent's Id
?
With delete, I mean that the SQL records in both tables should be deleted (resulting in a DELETE
SQL statement) after calling .SaveChanges()
.