Reputation: 27350
I have the following table defined through code-first:
public class Action
{
public int ActionId { get; set; }
public int? EmailMessageId { get; set; }
public virtual EmailMessage EmailMessage { get; set; }
}
public class EmailMessage
{
public int EmailMessageId { get; set; }
public string Content { get;set;
}
When an action is created with a corresponding EmailMessage, deleting the action doesn't remove the entry in EmailMessage. It seems EF only creates a cascade delete on 1-many relationships. In this case the relationship is 0 or 1 relationship which has no cascade delete set by default.
I then added the fluent configuration:
modelBuilder
.Entity<Action>()
.HasOptional(x =>x.EmailMessage)
.WithMany()
.HasForeignKey(x=>x.EmailMessageId)
.WillCascadeOnDelete(true);
Which seems to correctly set the CASCADE DELETE when viewing the schema in Management Studio. But when I remove the row from Action manually from the db, the row in EmailMessage remains.
What exactly am I doing wrong here? I thought I might be getting somewhere when I used 'WithOptionalDependent()' in the configuration. However when I looked at the schema, it had introduced "EmailMessage_EmailMessageId", when I already had EmailMessageId in the table?
Can anyone advise what is wrong here?
Upvotes: 0
Views: 939
Reputation: 1
I have just realized when using "contextName.Entry(parentStudySession).State = System.Data.Entity.EntityState.Deleted;" to delete some parent with a few children..I talk for EF 6.3, EF doesnt't delete the children for us, even didn't delete the parent itself even though we have got cascading on delete constraint. Instead, it gives an error "The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not ... "
Instead, when I use "contextName.StudySession.Remove(parentStudySession);" , EF 6.3 successfully deletes the PARENT and the CHILDREN... I have cascade on delete constraint. T.Adakoğlu
Upvotes: 0
Reputation: 35533
The cascade delete is designed to remove the child when the parent is deleted, not the other way around. In this case, the Action is the child associated with the foreign-key of the EmailMessage parent. So deleting the Action will not affect the EmailMessage, but deleting the EmailMessage should cascade delete to the Action.
Upvotes: 1