find a location for property in a new city

Friday, 17 May 2013

How to solve Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

I was writing my Entity Framework 5 Code First data models one day when I received a dramatic sounding error: "Introducing FOREIGN KEY constraint 'FK_dbo.Days_dbo.Weeks_WeekID' on table 'Days' may cause cycles or multiple cascade paths." I was instructed to "Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints." And then simply the message, "Could not create constraint." So what happened with my Foreign Key that makes it cyclic?"

First a spot of code that can nicely demonstrate this scenario:

public class Year
{
    public int ID { get; set; }
    public string Name { get; set; }

    public ICollection<Month> Months { get; set; }
}
public class Month
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Year Year { get; set; }
    public ICollection<Day> Days { get; set; }
}
public class Day
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Month Month { get; set; }
    public Week Week { get; set; }
}

//problem time
public class Week
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Year Year { get; set; }
    public ICollection<Day> Days { get; set; }
}

So, let's explain this. A Year has Months and a Month has Days - all is well at this point and it will build and generate all your tables happily. The problem comes when you add the highlighted parts to add Weeks into the data model.

By making those Navigation Properties you have implicitly instructed EF Code First to create Foreign Key constraints for you and each of these will have cascading deletes on them. This means, upon deleting a Year, the database will cascade that delete to that Year's Months and in turn those Month's Days. This is to, quite rightly, hold referential integrity; you will not have Yearless Months.

So if you think about it, now that we have added a Week entity that also has a relationship with Days this too will cascade deletes. So as well as the cascading deletes that occur when you delete a Year as I described above, now deleting a Year will also delete its Weeks and those Weeks will delete the Days. But those Days would have already been deleted by the cascade that went via Months. So who wins? Who gets there first? Don't know... that's why you need to design an answer to this conundrum.

Removing the multiple cascade paths

The way I found to solve this issue is you need to remove one of the cascades, since there is nothing wrong with the Foreign Keys, it is only the multiple cascade paths. So lets remove the cascading delete on the Week -> Days relationship since that delete will be taken care of by each Month cascading its deletes to their Days.

public class CalenderContext : DbContext
{
    public DbSet<Year> Years{ get; set; }
    public DbSet<Month> Months { get; set; }
    public DbSet<Day> Days { get; set; }
    public DbSet<Week> Weeks { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Day>()
            .HasRequired(d => d.Week)
            .WithMany(w => w.Days)
            .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
    }
}

If you already have a ForeignKey field explicitly written into your code model (as I usually do - I removed them from the above example for clarity) you will need to specify this existing Foreign Key in the code just written. So if your Day entity looked like this:

public class Day
{
    public int ID { get; set; }
    public string Name { get; set; }

    [ForeignKey("Month")]
    public int MonthID { get; set; }
    public Month Month { get; set; }

    [ForeignKey("Week")]
    public int WeekID { get; set; }
    public Week Week { get; set; }
}

You will need your OnModelCreating method to look like this:

modelBuilder.Entity<Day>()
    .HasRequired(d => d.Week)
    .WithMany(w => w.Days)
    .HasForeignKey(d => d.WeekID)
    .WillCascadeOnDelete(false);

Have fun deleting safely!

Follow britishdev on Twitter

70 comments:

  1. Legend has foretold that one day, someone will post a comment that is a complete sentence.

    ReplyDelete
  2. Thank you very much for your post, it makes us have more and more discs in our life, So kind for you, I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear.
    happy wheels| friv|monster high| shooting games| tetris| 8 ball pool
    cool math games| barbie games| friv4school| agario| fighting games

    ReplyDelete
  3. A great possibility for me and it was a superb knowledge to view this site. Very difficult to uncover these beneficial web page or web site. I have many devices and achieving proper picture of these worked well and energy continues to be seeing about this weblog. Often my own intend to make my personal site as well as my own enjoyment is growing due to this page. I we do hope you may well be more effective.
    happy wheels| cool math games| 8 ball pool| sudoku| yoob| friv| monster high
    tetris| shooting games| barbie games| friv4school|

    ReplyDelete
  4. Thank you! I have to thank you for the efforts you’ve put in penning this site.I really hope to check out the same high-grade blog posts by you later on as well. In truth, your creative writing abilities has motivated me to get my own website now !
    happy wheels
    super mario bros
    pacman
    agario

    ReplyDelete
  5. Business Homework Help
    Best Accounting Homework Help Available Since 2005! Get Assitance from Best Tutors, Best Services at Best Prices. No Registeration Required, Just Email Us.

    ReplyDelete
  6. Get Accounting Homework Help and assistance with other Subjects by Tutors.



    Finance Homework Help

    ReplyDelete
  7. Best Dissertation Writing Service & Coursework Writing Service Available in UK. 24/7 Experts & Writers Available. Very Reasonable Prices. No registeration required, Just Email us the Details. Get Free Outline and Proposal at Discounted Rates.
    Coursework Writing Service

    ReplyDelete
  8. Get the best Dissertation & Custom Essay Writing Service from our Qualified Writers. Trust the best and never regret. Try our Essay Help and see the difference in your grades.
    Essay Writing Service

    ReplyDelete
  9. Students strive hard to get good grades at colleges and universities. They spent immense time on the strenuous task of finding proper authentic sources and references for completing their coursework paper. Not all students possess the required analytical skills to write unique papers for each of the subjects they study as part of their college or university syllabus. At such a time, professional help is required for such students and http://courseworkwritingservice.co.uk does just that.

    ReplyDelete
  10. The biggest stumbling block preventing students from getting meritorious marks in their studies is writing their coursework papers flawlessly and submitting. The problem of the students is understandable. When it comes to writing essays, dissertation papers, research papers, thesis and term papers etc., the educational institutions prescribe certain quality standards, which the student community finds very hard to overcome.for more details click here - http://www.customdissertationwritingservice.co.uk

    ReplyDelete
  11. We provide custom coursework writing service. Coursework UK Help Available. Buy Coursework now at reaonable prices.
    Buy Coursework

    ReplyDelete
  12. Email your Assignments & Get the fastest College Homework Help! 24/7 Tutors & Writers available in all Subjects including accounting, finance, business, statistics! Essay, Dissertation Editing Service Available.
    Finance Homework Help

    ReplyDelete
  13. Thesis Writing Service or Dissertation Help, just send us an email and we will get that done by our qualified writers within deadline for resonable rates.

    Dissertation Writing Service

    ReplyDelete
  14. Every student faces an arduous task when asked to write down his or her thoughts on a paper. More so when it comes to completing an academic dissertation in stringent timelines. Writing a well researched and aptly presented dissertation while is not an easy thing yet is almost critical for the concerned person. They may seek for some outside help to complete the task in time while meeting all essential requirements. This is when the qualified service providers come into the picture with their vast experience of completing such projects with effectiveness. All that is required on the part of the student is to order what is needed and it will be done within the prescribed time span without errors.for more details click here - http://dissertationuk.co.uk/

    ReplyDelete
  15. Statistics Homework Help Available! SPSS or Excel? Send us your Statistics Assignments and Get them completed on time at rock bottom prices!
    Statistics Help USA

    ReplyDelete
  16. Do you find it tough to handle your financial assignments and fail to submit it within the stated deadlines? If yes, then Finance Homework Help offers you assistance to solve all your all problems and assignment related to finance. Be the first to submit your assignment without compromising with quality of the work and its accuracy. Get top grades with the work done by professionals within the deadline.for more details click here- http://thefinancehomeworkhelp.com

    ReplyDelete
  17. Are you an aspiring graduate and worrying about submitting a perfect top class dissertation? Do not worry as Dissertation Proposal Writing UK comes up with best possible writing solutions.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Buy Whey Protein In Pakistan and Get good LifeStyle and Healthness, more information visit our website thankyou!

    ReplyDelete
  20. We deal into custom coursework writing service. Best Coursework Help Available. Buy Coursework now at reasonable prices. Coursework Service USA

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete
  23. The students do not need to register at the site. They can simply email their coursework requirements at buycoursework@gmail.com to receive a free quote from the site. Payment methods accepted are credit card and PayPal. The customer service is prompt and customer information is kept confidential at the site. The professional team of writers at Thesis Writing Service
    can provide plagiarism-free coursework to students keeping in mind the deadlines. Double selling is not done at the site. The students receive complete satisfaction from the services of the company.

    ReplyDelete
  24. Qualified tutors are ready to provide you Statistics Homework Help, Accounting Homework Help & assistance with all other subjects including College Finance, Economics Assignments. You can also contact us for your Dissertation, Thesis or your other writing needs. Best Prices, Fast Response!

    ReplyDelete
  25. Term Paper Writing Service of many pages written to discuss a topic descriptively. Like essays, term papers are also intriguing and interesting to write for students as they help gain much knowledge about a specific topic.

    ReplyDelete
  26. Get Best Coursework Writing Help by Best Dissertation & Essay Writers. Just contact us with all the details and we will help you in getting it done.

    ReplyDelete
  27. The task of writing becomes tougher by the above stipulations, which are beyond their capabilities and experience.for more info visit- Dissertation Writer

    ReplyDelete
  28. The team at Accounting Homework Help is a well qualified group of tutors with mostly PhDs from best Universities.

    ReplyDelete
  29. Get custom written Marketing Essay,Thesis, Research Papers and Dissertation by trained Writers at very Reasonable prices.Essay Writing Service

    ReplyDelete
  30. Now a day people like to take writing as profession and there are many writers who have that excellence in the field of writing.Accounting Homework Help

    ReplyDelete
  31. Thus, when in such rush, sites like thecourseworkhelp.com can be beneficial as it gives you 24 hour service, with the promise of delivery on the required date. Coursework Help

    ReplyDelete
  32. All these services at AcademicEssayWritingService.com can be availed at a reasonable price and is just a click away. References and limitless modifications will be provided as well. No registration required, kept confidential and 100% satisfaction guaranteed. For more information click here - Essay Writing Service

    ReplyDelete
  33. This comment has been removed by the author.

    ReplyDelete
  34. The educational institutions all over the world adopt the system of allotting coursework assignments, homework, and writing of essays, thesis, research papers, dissertation papers and term papers etc.Promptly they will get the essay or academic paper written, which they can submit and reap meritorious marks. Just click Business Essay Writing Service and you will be glad you did!

    ReplyDelete
  35. Coursework Writing service has been known for the excellent academic help extended by them to thousands of students. The latter often find it difficult to complete their assignments successfully after their busy schedule. They often require certain online help in order to save time. Coursework Writing service to their rescue whenever they need any help regarding the assignments or coursework.

    ReplyDelete
  36. The popular services that Custom Dissertation Writing Service provides are:
    1. Paraphrasing
    2. Proof reading
    3. Term papers
    4. Course work
    5. Essay
    6. Dissertation
    7. Literature reviews
    8. Case study
    9. Research papers
    10. Book reviews and many more
    The Dissertation Writing Service providers promise you to deliver genuine quality work and that too within the stipulated time. You just have to trust them and the rest will be taken care of.

    ReplyDelete
  37. Best Dissertation Proposal Writing Service. We can also help with complete Dissertation Proposal Writing Service, Essay, Coursework or Thesis. Best Writers available!

    ReplyDelete
  38. Dissertation Writing Service helps the students, wherever they are in this world, in this ticklish problem of writing course work.

    ReplyDelete
  39. Are you looking for Cheap and best Essay Writing Service, stand out from our competition as the prime essay service provider.
    More to visit:http://www.academicessaywritingservices.org/

    ReplyDelete
  40. This comment has been removed by the author.

    ReplyDelete
  41. Wow today I am very happy because today I receive a great blog. This blog is about writing project. Long time I was finding http://www.boomerangreview.com/a-writer-com-review/. Blog writer describe their more details in his blog. Thank you so much for your good job.

    ReplyDelete
  42. Posts shared useful information and meaningful life, I’m glad to be reading this article and hope to soon learn the next article. thank you
    minecraft games
    g9g games
    a10 games
    yepi games
    hopy games
    kizi games
    friv games
    huz games
    4223 games
    kizi new games

    ReplyDelete
  43. The topic of this post is very informative for me which is about How to solve Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths. It increases my knowledge as well and I will must share it with others.
    Buy our best gym mats from http://ukgymmats.co.uk/gym-mats.html

    ReplyDelete
  44. Very nice. Posts shared useful information and meaningful life, I'm glad to be reading this article and hope to soon learn the next article. thank you
    minecraft
    g9g games
    a10 games
    hopy games
    yepi games
    kizi games
    friv games
    4223 games
    huz games
    kizi new games

    ReplyDelete
  45. Doctoral thesis can be purchased online through the e-services of reliable dissertation writing. You have options that can provide the name of the subject and the details of theses Author experts then go to work for you as per requirement.

    Cheap Dissertation Writing Services

    ReplyDelete
  46. Do your friends make fun of you for staying at home on weekends? Assignments make a lot of people work like this. Get them done from AllAssignmentHelp.
    Here

    ReplyDelete
  47. Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know.
    facebook lite |resignation letter|qr code generator

    ReplyDelete
  48. All the best blogs that is very useful for keeping me share the ideas
    of the future as well this is really what I was looking for, and I am
    very happy to come here. Thank you very much
    earn to die
    earn to die 2
    earn to die 3
    Hi! I’ve been reading your blog for a while now and finally got the
    earn to die 4
    courage to go ahead and give youu a shout out from
    earn to die 6
    Austin Texas! Just wanted to tell
    earn to die 5
    you keep up the fantastic work!my weblog
    age of war
    Hi! I’ve been reading your blog for a while now and finally got the
    happy wheels
    strike force heroes
    slither io
    slitherio
    good game empire

    ReplyDelete
  49. Friv is big derectory flash games online free for kids. My site add new-best games from Friv, Kizi, Y8, Yepi... Visit and play now, free for fun at Friv.wf!
    friv games | juegos de friv | gry Friv

    ReplyDelete
  50. Really impressive post. I read it whole and going to share it with my social circules. I enjoyed your article and planning to rewrite it on my own blog.
    gta 5 | www.google search | excel

    ReplyDelete
  51. The best space for your child to relax!: wingsio
    slither io

    ReplyDelete
  52. Let’s keep out sites for your child! click:
    slither.io | wings.io | happy wheels | abcya | fnaf 4 | games for kids | racing games to play for free!

    ReplyDelete
  53. very nice post thanks i like it thanks>>>>>

    jogos d moto

    ReplyDelete
  54. I found lots of interesting information here.Great work
    Thanks for the share loved reading the article, please do share more like this wiht us .

    Temple Run 2
    Run 3
    Click Jogos
    Subway Surfers

    ReplyDelete
  55. I want you to thank for your time of this wonderful read!!! I definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog!
    slither io | wings io | science kombat | tank trouble 4

    ReplyDelete
  56. The best space for your child to relax!: wingsio | slither io | ya

    ReplyDelete
  57. Welcomes to google terminal keep sharing such ideas in the future as well.
    google snake this was actually EARN TO DIE
    what i was looking for,and i am glad to came here! AGE OF WAR 2
    Hi! I’ve been reading your blog for a while HAPPY WHEELS
    I want you to thank for your time of this wonderful read!!! Slitherio
    Amazing insight you have on this, Slither io This article always blew me BIG FARM

    ReplyDelete
  58. When you see the stress in work, life, friv could well be a good site to try.
    Thanks you for sharing - See more at: baixar mobogenie, juegoskizi, juegoskizi, descargar whatsapp, descargar whatsapp, descargar mobogenie

    ReplyDelete
  59. Rolex Watches Authentic Mens & Ladies Rolex Datejust, President Watches for Sale at JavyEstrella.com.

    ReplyDelete
  60. A great possibility for me and it was a superb knowledge to view this site. Very difficult to uncover these beneficial web page or web site. I have many devices and achieving proper picture of these worked well and energy continues to be seeing about this weblog. Often my own intend to make my personal site as well as my own enjoyment is growing due to this page. I we do hope you may well be more effective.
    jeux de fille
    العاب طبخ جديدة
    girl games 2017
    لعبة الراقصة الجميلة
    باربي في الفضاء

    ReplyDelete
  61. I was working and suddenly I visits your site frequently and recommended it to me to read also. Age Of War 2
    Big Farm | Slitherio
    Tank Trouble | Happy Wheels
    Goodgeme Empire | Slither.io

    ReplyDelete