C# – Foreign Keys in Entity Framework – Code First – Query with Linq

In this article, I present an Entity Framework example, building two tables with foreign keys, using code first. The sample I am using is building over the previous article for EF.

Pretty much, when you are running your application, if you receive the fancy message during C# execution “Cannot drop database because it is currently in use“, although you are having  Database.SetInitializer(new DropCreateDatabaseAlways<SomeDbContext>());  then it is time to run this query:

The easiest way to execute it is to select the DB from the SQL Server Object Explorer, create a new SQL document and press Ctrl+Shift+E:

Start

At first we need 2 classes  – Company.cs  and Car.cs. The properties of these classes would be the columns in the tables corresponding to these in our DB:

In order to tell our DbContext, that these two classes are actually DB tables and should be created, a DbContext class is needed. Or something, that inherits it:

So, what can we do with these beautiful classes? We may ask EF to create a DB and make the classes a table. Then EF may enter some data in them with loops. Quite an easy and self-explanatory method:

The query in Linq is interesting. We need to unite two tables and print all the cars in all the companies, which are with country of origin Bulgaria or Italy. This is the query sample:

And this is what it prints:

Pretty much this is all. The whole code is in GitHub here.

Enjoy it 🙂

Tagged with: , , ,