Entity Framework – Database First Approach Example

2

 

Database First allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The poco classes are automatically generated from the EDMX file.

4

 

Entity Framework – Database First Approach Example

1. Let’s create a console application. Name it as “EFDatabaseFirstExample”.

2. We will create a model by using Entity Framework Designer for our existing database. Let’s add a new item to our project “ADO.NET Entity Data Model”.

3. It will start a wizard, now as we have existing database, we will select “Generate from Database”.

4. Choose the connection string, pick a connection to our existing database and click on “Next” button.

5. Wizard will ask you to pick the Entity Framework version to use. Just select the latest version and click “Next”.

6. Now choose the database objects like tables, views, stored procedures etc from the screen.

7. Model is created now and you can see the entities.

8. During the process when you select Entity Framework version, the reference to Entity Framework Assembly is automatically added.

So after step 7, you will see following things in the project.

9. Since everything is in place, let’s code to add a employee for a company and display all the employees for a company.

1

EFDatabaseFirstDBEntities db=new EFDatabaseFirstDBEntities();

Companies obj=new Companies();

Obj.Name=”Sandip Patil Company”;

Obj.Address=”Pune”;

db.AddToCompanies(obj);

db.SaveChanges();

 

Leave a comment