1

I have a question about cascade deletes in sql server. I have two tables: Employee and Degree with a one to many relation. Now I want to delete Employee, but I get an error because there is a relation with degree. How can I delete the related information when I delete an employee?

After research I found that you can use cascade delete. I tried this without success. I have read the following topics.

How do I use cascade delete with SQL Server?

I have added this code to my EmployeeController, without success

    protected void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Employee>()
            .HasMany(x => x.Degrees)
            .WithRequired(x => x.Employee)
            .WillCascadeOnDelete();
    }

And I tried changing the delete option to cascade, what is shown in this topic:

SQL Server 2005 Cascading Delete

But so far without success. So how can I delete an employee with his relations.

Community
  • 1
  • 1
Barry The Wizard
  • 1,258
  • 2
  • 12
  • 25
  • Please show the code that you used without success. – Gordon Linoff Oct 23 '16 at 15:45
  • What you try so far ? please add the code you try it – Ilyes Oct 23 '16 at 16:05
  • Does Degree Table Have any other relations (Foreign Keys)? – Hadi Oct 23 '16 at 16:14
  • Please provide the exact error message you are getting. Also, did you only define the cascading delete in the code you posted? Or is it also defined at the database level? They are potentially 2 different things. Also, things like lazy loading can have an impact, so you really also need to provide an [MVCE](http://stackoverflow.com/help/mcve). – sstan Oct 23 '16 at 16:17
  • `OnModelCreating` should be defined in a `DbContext` rather than a controller. – Jonathan Lonowski Oct 23 '16 at 16:38

0 Answers0