Disable Cascade Delete EF6

cascade ef-code-first entity entity-framework-6

Question

I'm trying to disable cascade delete using EF6 code-first.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}

When I try to delete a record in table I get an error

"The primary key value cannot be deleted because references to this key still exist. [ Foreign key constraint name = FK_dbo.OperatorActivity_dbo.Operator_OperatorId ]"

My models

public class OperatorActivity
{
    public Guid Id { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public bool Synched { get; set; }

    public virtual Station Station { get; set; }
    public Guid StationId { get; set; }

    public virtual Operator Operator { get; set; }
    public Guid OperatorId { get; set; }
}

public class Operator
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Login { get; set; }
    public byte[] Password { get; set; }

    public virtual  Network Network { get; set; }

    public virtual ICollection<Station> Stations { get; set; }
    public virtual ICollection<OperatorActivity> Activities { get; set; }
    public virtual ICollection<Refill> Refills { get; set; }

    public override string ToString()
    {
        return this.Name + " " + this.LastName;
    }
}

How can I disable cascade delete?

1
2
7/3/2015 1:58:23 PM

Popular Answer

Though it is not logical to remove referenced (parent) rows while keeping child rows, to be allowed to do that, you should drop the foreign key constraint.

In MySQL database run:

alter table OperatorActivity drop 
foreign key FK_dbo.OperatorActivity_dbo.Operator_OperatorId

In SQL Server:

alter table OperatorActivity drop 
constraint FK_dbo.OperatorActivity_dbo.Operator_OperatorId
1
7/3/2015 12:51:27 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow