2

Is it possible to prevent cascade delete from a single way with Entity Framework Code-First.

Here is a sample code:

public sealed class ZeContext : DbContext
{
    static ZeContext()
    {
        Database.SetInitializer(new CreateDatabase());
    }

    public IDbSet<A> As { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<A>()
            .ToTable("A")
            .HasMany<B>(a => a.Bs)
            .WithMany(b => b.As)
            ;

        modelBuilder.Entity<B>()
            .ToTable("B")
            .HasMany<A>(b => b.As)
            .WithMany(a => a.Bs)
            ;

        base.OnModelCreating(modelBuilder);
    }
}

public class A
{
    public Guid Id { get; set; }
    public virtual ICollection<B> Bs { get; set; }
}

public class B
{
    public Guid Id { get; set; }
    public virtual ICollection<A> As { get; set; }
}

I would like to configure the following behaviour:

  1. When deleting a record from table A, it should remove the corresponding association records from the internal many-to-many table created by EntityFramework.
  2. However, when deleting a record from table B, it should fail if there is a corresponding association record in the internal many-to-many table.
Maxime Labelle
  • 3,609
  • 2
  • 27
  • 48
  • I found the answer here and it worked for me: http://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations – Roger Mar 23 '15 at 19:24

0 Answers0