Entity Framework Code First Approach

Entity Framework Code First Approach

In this blog, you will learn about the Entity Framework Code First Approach.

Introduction

Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database. ORM framework automatically creates classes based on database tables and the opposite is also true; that is, it can also automatically generate necessary SQL to create database tables based on classes.

First we need to install Entity framework and the best way to install that is by using: -NuGet Package Manager.

Code first approach allows us to create our custom classes first and based on those classes entity framework can generate database automatically for us.

Step 1

Create New Project - Select Web Application- Select MVC Template - Cick OK.

Step 2

Go toTools - NuGet Package Manager - Manage NuGet Packages For Solution - Browse and type Entity Framework click on Install

Step 3

Add the following classes in the Model Folder of your project.

  1. using  System.Collections.Generic;  
  2. using  System.ComponentModel.DataAnnotations;  
  3. using  System.ComponentModel.DataAnnotations.Schema;  
  4. namespace  CodeFirstApproach.Models  
  5. {  
  6. [Table( "tblClass" )]  
  7. public  class  Class  
  8. {  
  9.    [Key]  
  10.    public  int  ClassID { getset ; }  
  11.    public  string  ClassName { getset ; }  
  12.    public  List Students { getset ; }  
  13.    public  List Courses { getset ; }  
  14. }  
  15. }   
  16.    
  17.    
  18. [Table( "tblStudent" )]  
  19. public  class  Student  
  20. {  
  21.    [Key]  
  22.    public  int  StudentID { getset ; }  
  23.    public  string  StudentName { getset ; }  
  24.    public  Class Class { getset ; }  
  25. }  
  26.    
  27. [Table( "tblCourse" )]  
  28. public  class  Course  
  29. {  
  30.    [Key]  
  31.    public  int  CourseID { getset ; }  
  32.    public  string  CourseName { getset ; }  
  33.    public  List Classes { getset ; }  
  34. }  

Step 4

Add another class as a Context Class and add connection string in web.config. In class add DbSet where each DbSet will map to a table in the database. If we have a property DbSet of Students, and the name of that property is Students, the Entity Framework will by default look for a Student table inside the database which in our case is tblStudent as we used [Table("tblStudent")] as Annotation .

  1. public  class  StudentContext: DbContext[DBContext maps to a specific database that has a schema that the DBContext understands] {  
  2.     public  StudentContext(): base ( "name=conn_StudentDB" ) {}  
  3.     public  DbSet < Class > Classes {  
  4.         get ;  
  5.         set ;  
  6.     }  
  7.     public  DbSet < Student > Students {  
  8.         get ;  
  9.         set ;  
  10.     }  
  11.     public  DbSet < Course > Courses {  
  12.         get ;  
  13.         set ;  
  14.     }  
  15. }  
  16. protected  override  void  OnModelCreating(DbModelBuilder modelBuilder) {  
  17.     modelBuilder.Entity < Class > ().HasMany(s => s.Courses).WithMany(c => c.Classes).Map(cs => {  
  18.         cs.MapLeftKey( "ClassId" );  
  19.         cs.MapRightKey( "CourseId" );  
  20.         cs.ToTable( "tblClassCourse" );  
  21.     });  
  22. }  
  23. }  

Step 4

Add another class as a Context Class and add connection string in web.config.In class add DbSet where each DbSet will map to a table.

Note 

We could also say that DBSet class represents an entity set that is used to create, read, update, and delete operations.

code visual studio code visual studio

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

COMO USAR e trabalhar com Code Review no Visual Studio Code

💲 Live CollabPlay: https://youtu.be/B6LCFSPdsE0 💲 Hospedagem com Desconto Exclusivo: https://tekers.tech/4e587 Não é todo programador que gosta de compartilh...

User Snippets (Code Shortcuts) in Visual Studio Code

#vscode Hello, my friends and fellow developers, this video is all about User Snippets. That means the Snippets (Code Shortcuts) that you can make for yourse...

Python в Visual Studio Code

We are pleased to announce that the July release of the Python extension is now available for Visual Studio Code. You can download the Python extension from the Marketplace, or install it directly from the extension gallery in Visual Studio Code. If you already have the Python extension installed, you can also get the latest update by restarting Visual Studio Code. You can read more about Python support in Visual Studio Code in the documentation .

C++ Development with Visual Studio Code

If you’re looking for a fast and lightweight open-source code editor, Visual Studio Code has you covered. Come for a deep dive into the features of Visual Studio Code which provide a rich, productive environment for C++ development.

The History of Visual Studio Code

We speak to the creator of Visual Studio Code about the early challenges to now becoming the most popular development environment in the world.