0

when I create my DbContext, I want all tables in my database to have delete-cascade enabled. Is it possible?

I have two tables with FK. The classes are

public class Child
{
    public int ChildID { get; set; }
    public string Name { get; set; }
    public virtual Parent parent { get; set; }
}

public class Parent
{
    public int ParentID { get; set; }
    public string Name {get;set;}        
}       

public class iMyContext : DbContext
{
    public iMyContext(string connectionString)
        : base(connectionString)
        {
        }


    public virtual DbSet<Child> Children { get; set; }
    public virtual DbSet<Parent> Parents { get; set; }  
}

On creating my context, I get tables as

Parents with columns
ParentID PK
Name

Children with columns
ChildID PK
Name
Parent FK

Now when I add

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
        .HasOptional(r => r.Parent)
        .WithRequired(ad => ad.)   // problem here
        .WillCascadeOnDelete();

    }

The WithRequired clause does not have Child. How do I solve that?

Jack Gray
  • 309
  • 2
  • 14

1 Answers1

1

Cascade delete could be setup using FluentAPI in OnModelCreating method:

modelBuilder.Entity<Root>()
            .HasMany(r => r.Nodes)
            .WithRequired(n => n.Root)
            .WillCascadeOnDelete();

UPD: Lets assume you have two entities Root and Node, which are connected with one-to-many relationship using DataAnnotations attributes:

public class Root
{
    [Key]
    public int RootId { get; set; }

    public string RootName { get; set; }

    [InverseProperty("Root")]
    public ICollection<Node> Nodes { get; set; }
}

public class Node
{
    [Key]
    public int NodeId { get; set; }

    public string NodeName { get; set; }

    [ForeignKey("Root")]
    public int RootId { get; set; }

    public Root Root { get; set; }
}

Now if you want to delete all Nodes while deleting the Root they're depend on, you need to configure this using FluenAPI in OnModelCreating method of your context configuration class using the code I introduced above before the UPD.

Nozim Turakulov
  • 869
  • 1
  • 9
  • 19
  • What is ? What is FluentAPI? Is it separate which I have to install? – Jack Gray Aug 18 '15 at 06:43
  • @JackGray As you didn't add any code sample in your question I named your assumed main (which is one) entity class as Root and the dependent entity class (which are many) as Node. Check an update for my answer. If you don't know what is FluentAPI you better to read a entity framework tutorial first. One of them you can find here: [entityframeworktutorial](http://www.entityframeworktutorial.net/) – Nozim Turakulov Aug 18 '15 at 06:48
  • I have updated my question with code and the problem – Jack Gray Aug 18 '15 at 07:35
  • I see the problem. You have added Nodes as InverseProperty, I don't create that and my application works fine without it – Jack Gray Aug 18 '15 at 07:41