I’ve been struggling with getting the EF CodeFirst right so that it automatically generates foreign keys when the tables are created. I had noticed that there is interesting syntax you can put in to create these foreign keys, however it seemed that the relationships are known so CodeFirst should do that for you. I won’t even bother to go through all the mistakes I made, but if you want to see one, you can check out my forum post where I ask for help.
I’m currently writing a series of articles on building a Sencha ExtJS application with Microsoft ASP.NET MVC3. I use codefirst and at the moment I’m building a database of US Presidents and linking them to their Party (republican, democrat, etc.). So, the important thing is to link from the Presidents table to the Party Table and also from the Party to the President. Below is the code:
And, the repository is defined as follows:
Notice that in the party class, there is a virtual ICollection of Presidents, and notice in the President class, there is a virtual reference to the Party. These combined make the relationship work and the foreign key created.
If I look in my SQL Database, you’ll see a new foreign key is automatically created for me as Party_id.
I’m not exactly sure how SqlExpressCE shows foreign keys, but I know it is there because when I try to delete a Party record that is associated with a President I get the following error:
which tells me there is a constraint called Party_Presidents (my foreign key).
So, it worked! If you want to see the full source for this, keep an eye on the series of articles I’m now writing (only the first one is done, but probably, by the time you find this, I’ll have others done that include this Presidents example. You can find the first one at the URL: http://peterkellner.net/2011/11/04/building-an-senchas-extjs-4-0-mvc-application-with-microsofts-asp-net-mvc3-series-basics/