EF4 CPT5 Code First Remove Cascading Deletes
Posted
by Dane Morgridge
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Dane Morgridge
Published on Fri, 17 Dec 2010 18:50:50 GMT
Indexed on
2010/12/18
17:14 UTC
Read the original article
Hit count: 398
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.
© Geeks with Blogs or respective owner