Evgeny Belov
Evgeny Belov

Reputation: 338

Disable Cascade Delete EF6

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?

Upvotes: 2

Views: 3872

Answers (1)

Ormoz
Ormoz

Reputation: 3011

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

Upvotes: 1

Related Questions