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

1

6

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

Maledict answered 8/12, 2010 at 0:16 Comment(0)
D
14

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);
    }
}
Ducharme answered 8/12, 2010 at 2:57 Comment(2)
Thanks Morteza, just saw the post myselfMaledict
No problem, Happy Code-Firsting :)Ducharme

© 2022 - 2024 — McMap. All rights reserved.