Skip to main content

Code First Getting Started

In this tutorial let us create a simple application to demonstrate the use of entity framework using code first.

We are using Visual Studio 2015 and entity framework 6.1.3. You can download Visual Studio community Edition . You should have the basic knowledge of .Net framework, C# and MS SQL Server.
In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user.

Create the Project

  1. Open Visual Studio.
  2. File ->New -> Project
  3. Select C# ->
  4. Select Console Application
  5. Name the application as “EFGettingStarted”
  6. Click on OK

Install Entity Framework

The next step is to install the Entity framework. This can be installed via nuget package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command
This will install the latest version of the Entity Framework (6.1.3).

Entity Type

The next step is to create the Entity Data Model (EDM)
  1. Select the Project
  2. Right click and click on add -> Class
  3. Name the class as Model.cs
  4. Copy the following code to the model.cs
We are done with our entity model.

DBContext

The DbContext (often referred as context) is the class which is responsible for interacting with the entity model and the data store. It allows you to query, insert, update and delete operations on the entities. This class is derived from the system.data.entity.dbcontext namespace. The older version of the entity framework used objectContext. DbContext is actually a wrapper around the objectContext class.
DbContext is responsible for the following

Database

DbContext is responsible for creating the Database instance for the context. It allows you to create,delete, check for the existence of the underlying database.

Connections

DBcontext manages connections to the database. It Opens the connections when needed and closes it when finished the processing of the query

Entity Set

DbContext exposes the property (DbSet<TEntity>) which represent collections of entities in the context. DbContext manages these entities during the lifetime of the entities.

Querying

DbContext converts LINQ-to-Entities queries to SQL query and sends it to the database.

Change Tracking

DbContext tracks the changes done to the each entity in its lifetime. It maintains the state of each entity (Added, Unchanged, Modified, deleted and detached).

Persisting Data

DbContext performs the CRUD operations to the database to persist the data.

Caching

DbContext does first level caching by default. It stores the entities which have been retrieved during the lifetime of a context class.

Manage Relationship

DbContext also manages associations between using data annotations/fluent API.

Materialization

DbContext translates the results returned by the underlying database into entities. This process called as materialization

Configuration

DBContext Provides API to which allows us the configure the behavior of the context.

Creating the Context

You can add a DbContext in your project by creating a class which derives from the DbContext class
  1. Select the Project
  2. Right Click -> Add -> Class
  3. Name the class as EFContext.cs
  4. Click on Add
  5. Import the namespace System.Data.Entity
  6. Make the EFContext class as public and inherit it from the DbContext class
Now we have added the Context class EFContext to our project

DBSet

As mentioned above DbContext class exposes the generic version of  DbSetwhich represents the collection of entities (entity set). Each entity type must expose the DbSet property so that they can be used in CRUD Operations
DbSet provides the methods to manage the entity set. To Add DbSet Property to your class add the following in the context class
Finally, our EFContext class looks like this

Adding data

We have defined our model (user class) and the context (EFContext). Now it is time to create a new user
Select the program class
In the main method of the class, paste the following code
In the above code, we created a new user instance. Then, we created an instance of DbContext object. The DbContext returns the Users Entity set (DbSet<TEntity>). We invoked the add method of the Users object and passed the newly created user instance. Finally, we invoked SaveChanges method of the DbContext object to save the changes to the database.
Now we are ready to test our application. Run the Application. If everything is ok then you should see “press any key to close” message. Press any key and console window will close.

Where is the database

We have not defined our database connection string. The Code first smart enough to create the database. Code First uses a series of steps to find and initialize the database. The Process is called database initialization.
Code First creates the database in localdb. (In older version of Visual studio SQL Server Express).
In Visual Studio go to View->SQL Server Object Explorer. You should see (localdb)\V11.0 under the SQL Server. (If you have installed SQL Server 2014 or Visual Studio 2015, then the localDb is available at (localdb)\MSSQLLocalDB). Expand the database and You will see that the database by the name “EFGettingStarted.EFContext” is created.
Code First in Entity Framework
Code First in Entity Framework
As you can see from the above image, Entity Framework has created users table with the column for each property. Few important things to note that
  1. Database was automatically created by EF
  2. Name of the database is “EFGettingStarted.EFContext”, which is fully qualified name of DbContext object
  3. Table names are pluralized. Our Entity class name was User. Table name is Users
  4. Column UserID is automatically configured as Primary Key.
  5. The UserID is also configured as identity column
The Code First does this by using Code-first conventions. It uses the model to create the database and build the tables and columns of the tables.

Conclusion

In this tutorial, we have created a simple application and learned how entity framework works

Comments

  1. R b88.bet - The Top Bet on Sports
    R b88.bet is 바카라사이트 a sports betting website that 우리카지노 was established in 2003. In the past year, it has also received a number of significant ratings and reputation rb88 awards

    ReplyDelete

Post a Comment

Popular posts from this blog

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome

First, FirstOrDefault, Single, SingleOrDefault In C#

For people who are new to LINQ, it is difficult to understand the difference between First, FirstOrDefault, Single, SingleOrDefault. In this blog, I will explain what to use and when.     I will take a simple example to make you understand practically how these methods work.   Consider a class Employee with properties as Id, Name, and Department. class  Employee {    public   int  Id {  get ;  set ; }    public   string  Name {  get ;  set ; }    public   string  Department{  get ;  set ; } } I have a list of Employees: List<Employee> employeeList =  new  List<Employee>(){    new  Employee() { Id = 1, Name =  "Sunny" , Department =  "Technical"  },    new  Employee() { Id=2, Name= "Pinki" , Department = "HR" },    new  Employee() { Id=3, Name= "Tensy" , Department = "Finance" },    new  Employee() { Id=4, Name= "Bobby" , Department = "Technical" },    new