Entity framework code first - 1

Entity Framework is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

The key features of using Entity Framework are Model and Context. Model contains the set of domain classes which represents each table of your database. Context represents a session with the database which allow us to query and save data.

Any Entity Framework application is made to center any one database server like MS SQL Server, MySQL, Oracle, etc., but this is highly plausible that we have to make an application which is database platform independent and requires minimal code change and uses same model and context to connect any database server which has same database.

In this blog I’m going to demonstrate that how to achieve this target in Entity Framework using code first approach:

Pre-requisites:

Before we are going to start, I suggest you to follow the steps mentioned in this MSDN blog which I used to develop most of my application: https://msdn.microsoft.com/en-us/library/jj200620(v=vs.113).aspx

Modify App.config file:

After you have successfully created your application, you will see that your App.config file have entity framework configuration and connection string. If you want your application to connect to any other database server you need to modify both of them.

In my example, I have created the application using MS SQL Server database and I’ll use same application to connect MySQL database.

Here is my App.config generated by Entity Framework while connecting MS SQL Server database:

Entity framework code first - 1

And this the App.config file with modified entity framework configuration and connection string for MySQL database:

Entity framework code first - 2

Check your output:

Here is the output when application is ran using MS SQL Server database:

Entity framework code first - 3

And while using MySQL database:

Entity framework code first - 4

Leave a Reply

Recent Comments

    Archives

    Categories