Entity Framework Database First approach is also known as Schema First Approach; this is the most popular or easy approach that new developer start with entity framework development, in this approach object gets generated from database directly.
As a developer, if you are already familiar with SQL Database development, then this approach can help you in rapid application development.
Step 1: right click on your .net project and add an "Ado.Net Entity Data Model" file as shown below. the file extension would be .edmx
Step 2:
Now you can either create an empty model or create a model from database,
(in this example we create a model from existing database), so select "Generate from Database".
Step 3:
To connect database, you can create existing connection from list or create a new connection, here we create a new connection, so you can learn how to create a new connection, look at the picture below, and please use “SQL server authentication”, so the same user name and password can be used in connection string configuration.
Step 4:
After connecting to database, Fetch all database objects you want to use in this application, also instead of fetching all you can chose objects you want in application by checking check boxes.
Stp 5:
Now your edmx file is loaded with database object information, so compile the project before you start writing code for database update and make sure you have set the connection string details properly.
Step 6:
Now our entity framework is ready to perform any database operation, so let’s create an instance of DbContext class and start working with database.
Here is an example how you can create an instance of DbContext
public tbStudent getStudent(int id) { tbStudent _student = null; using (Entities context = new Entities()) { _student = context.tbStudents .Where(s => s.studentId == id) .FirstOrDefault<tbStudent>(); } return _student; }
While creating new instance of context object, always do with using keyword, then we don’t have to dispose the object after use, once it comes out of the scope, it will be disposed automatically