Dane Morgridge

Programmer, Geek, ASPInsider
A blog about code and data access

  Home  |   Contact  |   Syndication    |   Login
  43 Posts | 0 Stories | 67 Comments | 0 Trackbacks

News

INETA Community Speakers Program

Twitter












Archives

Post Categories

I have been using EF4 CTP5 with code first and I really like the new code.  One issue I was having however, was cascading deletes is on by default.  This may come as a surprise as using Entity Framework with anything but code first, this is not the case.  I ran into an exception with some one-to-many relationships I had:

Introducing FOREIGN KEY constraint 'ProjectAuthorization_UserProfile' on table 'ProjectAuthorizations' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

To get around this, you can use the fluent API and put some code in the OnModelCreating:

   1: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
   2: {
   3:     modelBuilder.Entity<UserProfile>()
   4:         .HasMany(u => u.ProjectAuthorizations)
   5:         .WithRequired(a => a.UserProfile)
   6:         .WillCascadeOnDelete(false);
   7: }

This will work to remove the cascading delete, but I have to use the fluent API and it has to be done for every one-to-many relationship that causes the problem.

I am personally not a fan of cascading deletes in general (for several reasons) and I’m not a huge fan of fluent APIs.  However, there is a way to do this without using the fluent API.  You can in the OnModelCreating, remove the convention that creates the cascading deletes altogether.

   1: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
   2: {
   3:     modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
   4: }

Thanks to Jeff Derstadt from Microsoft for the info on removing the convention all together.  There is a way to build a custom attribute to remove it on a case by case basis and I’ll have a post on how to do this in the near future.

posted on Friday, December 17, 2010 1:50 PM