Trusted answers to developer questions

What is Entity Framework?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Entity Framework

Entity Framework is an object-relational mapping framework for .NET applications. Object-relational mapping allows the use of database queries and operations with object-oriented programming languages.

svg viewer

Usage

Step 1: First, a database model will be defined using Entity Framework. In this example, a simplified database for shots will be created with only the shots’ URL and stored content:

using Microsoft.EntityFrameworkCore;
namespace EducativeEF
{
public class ShotContext : DbContext //DbContext allows manipulation of the database
{
public DbSet<Shot> Shots //DbSet is the collection of entities in the context
{
get;
set;
}
//To configure the database we use the DbContextOptionsBuilder class
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=shots.db");
}
public class Shot //Define the Shot class
{
public string url
{
get;
set;
}
public string content
{
get;
set;
}
}
}

Step 2: Next, the database has to be created. The method of creation depends on the IDE being used. For users of the .NET Core CLI, the following lines will be used:

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

For Visual Studio users, the following needs to be run in the PowerShell:

Install-Package Microsoft.EntityFrameworkCore.Tools
Add-Migration InitialCreate
Update-Database

Step 3: Now, entries can be made to the database:

namespace EducativeEF
{
class EntityFramework
{
static void Main()
{
using (var shotDb = new ShotContext())
{
//This function adds new records to the database
shotDb.Add(new Shot( url = "www.educative.io", content = "Entity Framework" ));
shotDb.SaveChanges(); //This function makes changes permanent
}
}
}
}

Step 4: For this example, the URL for Educative’s homepage is stored and the content for the shot is “Entity Frameworks”. The following code can be used to make a query:

namespace EducativeEF
{
class EntityFramework
{
static void Main()
{
using (var shotDb = new ShotContext())
{
// The resultant shot of this query is store in queryShot
var queryShot = db.Shots.OrderBy(s => s.content).First();
}
}
}
}

This query returns the first shot when shots are sorted in alphabetical order based on their content.

Of course, there are other operations that can be carried out using Entity Frameworks with different kinds of databases. There are also different methods to initialize Entity Frameworks into projects.

RELATED TAGS

c#
databases
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?