Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"?

like image 355
merbla Avatar asked Dec 08 '10 00:12

merbla


1 Answers

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);
    }
}
like image 184
Morteza Manavi Avatar answered Oct 13 '22 11:10

Morteza Manavi