How to Switch Cascade delete off in a One to Many Relationship with EF CTP5 Fluent API

.net, code-first, entity-framework, entity-framework-4, entity-framework-ctp5

Solution

If you have a one to many relationship in your model, EF code first will enable cascade delete by default convention. So you don't really need to do anything special, but let's consider a scenario that you want to override the convention and switch cascade delete off. This is how it gets done by the Fluent API came with EF CTP5 earlier today:

public class Customer
{
    public int CustomerId { get; set; }        
    public virtual ICollection<Order> Orders { get; set; }
}

public class Order
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }        
    public virtual Customer Customer { get; set; }        
}

public class StackoverflowContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>()
                    .HasMany(c => c.Orders)
                    .WithRequired(o => o.Customer)
                    .HasForeignKey(o => o.CustomerId)
                    .WillCascadeOnDelete(false);
    }
}

Problem

In Fluent NHibernate you are able to set the cascade settings for a mapping e.g. ``` public class StoreMap : ClassMap<Store> { public StoreMap() { Id(x => x.Id); Map(x => x.Name); HasMany(x => x.Staff) .Inverse() .Cascade.None(); HasManyToMany(x => x.Products) .Cascade.All() .Table("StoreProduct"); } } ``` How is this done in Entity Framework "Code First"?

Original source