Wriju's BLOG

.NET, Cloud and everything

Using ADO.NET EF 4.1 Code First with existing Database

Most of the time questions comes to our mind about EF 4.1 Code First whether or not can we use it with already available database? Simple answer is YES.

I have very few personal view on it. I have seen in most of my application development scenario, database gets designed and created before and then evolves as application and requirements. So I expect to use Code First with already created database.

This is how we can,

image

Step 1: We will go for the database-first approach and create our EDMX.

image

Step 2: Right click on the edmx and then choose “Add Code Generation Item…

image

Step 3: Select “ADO.NET DbContext Generator”. Then delete the .edmx file from your project.

After that you need few small but important changes,

Change 1 : Add the connection string (if using SQL Server)

image

Change 2 : The tables you are using in your code (check all the DbSet<T> in your context) and add their corresponding onModelCreating code

image

Then your code should run without any trouble,

image

Namoskar!!!