How to switch Cascade delete off in a one-to-many relationship with the EF CTP5 Fluent API

In Fluent NHibernate, you can set up cascading settings for display, for example.

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 the Entity Framework "Code First"?

+6
entity-framework entity-framework-4 code-first entity-framework-ctp5
source share
1 answer

If your model has a one-to-many relationship, the EF code will first allow cascading deletion by default. This way, you really don't need to do anything, but consider the script you want to override and disable cascading deletion. Here's how to do it using the Fluent API with EF CTP5 earlier:

 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); } } 
+14
source share

All Articles