Working with Entity framework (Code First)
Entity Framework is the ORM that has been pushed by the MSFT giant over the last few years to the .NET community.
Entity framework comes in two flavors
Code First and
Code first is MSFT’s way of using Entity Framework to scaffold your database from code. This huge feature allows you, the developer, to not write any SQL to create the database.
MSFT’s tutorials with EF really push you toward having Entity Framework create the database, and use some
Linq tricks to generate all the SQL. Now one of the huge downsites to this philosophy is that there is no stored procedures you can magically change to fix any database performance issues. This means any changes to alter the way you query should be done with a new deployment of the application. This also means that you will not have the oppertunity to profile any sprocs, and try to gain CPU cycles in the database. If you are looking for high performance I would look toward using Dapper instead. The benefit for using EF, is honestly developer time. You can get started much faster using Entity Framework’s code first approach.
To put it simply make a class(or classes) and make a context which contains a
set of those classes. Make sure you first add the entity framework nuget package.
then in the package console window type
enable-migrations this will create a migrations folder and a configuration. If you wish your code to auto create the database on start, then add
AutomaticMigrationsEnabled = true; to the
Configurations.cs file that is created.
Then simply type
add-migration give it a name, and the migration will look something like the following.
You can then type update-database, and it will update the database. Note: the connection string is defined in the web config, and is declared on the following line.
See we have a connectionstring in our webconfig called DefaultConnection, and using our base constructor we are naming that as our connection.