Written by 09:01 Frameworks, Languages & Coding

Entity Framework – Just a Few Clicks Away

CodingSight - Entity Framework - just a few clicks away

Entity Framework is an open-source object-relational mapping (ORM) framework for .NET applications. It let the developers work with data on a higher level of abstraction without the need to worry about the database type or structure where the data is stored.

The focus of this article will be to show and explain how easy it is to add an Entity Framework to a .NET project.

Entity Framework saves a lot of time and effort to .NET developers. After setting it up once, we don’t need to worry anymore about the database tables or columns. Developers can work with the data using .NET objects, with less code, and without the need to handle any database-related tasks.

The following image shows where EF fits into a 3-layered architecture.

Entity Framework fits into a 3-layered architecture

Entity Framework Features

  • Cross-platform – runs on Windows, Linux, and Mac
  • Modeling – creates Entity Data Model (EDM) and uses it when querying or saving data to the database
  • Querying – supports LINQ queries along with raw SQL queries directly to the database
  • Change Tracking – keeps track of changes in the instances of entities
  • Saving – SaveChange and SaveChangesAsync methods perform INSERT, UPDATE, and DELETE commands to the database based on the changes in the data model
  • Concurrency – uses Optimistic Concurrency to protect against issues if multiple users access the data
  • Transaction – uses automatic transactions management
  • Caching – includes the first level of caching. This means that repeated querying will return data from the cache instead of hitting the database
  • Built-in Conventions – follows conventions over the configuration programming pattern and included a set of default rules which automatically configure the EF model
  • Configurations – supports the usage of data annotation attributes
  • Migrations – provides a set of migration commands that can be executed to create of update database schema

Add Entity Framework to Your Project

In our previous LINQ-focused article, we made the data model. To save time, we will define our model again here.

public class Student 
{ 
public int Id { get; set; } 
public string FirstName { get; set; } 
public string LastName { get; set; } 
public int BirthYear { get; set; } 
public enum GenderType { Female, Male }; 
public GenderType Gender { get; set; } 
public string Interests { get; set; } 
} 
public class StudentProfile 
{ 
public string FullName { get; set; } 
public int Age { get; set; } 
public Student.GenderType Gender { get; set; } 
public string[] Interests { get; set; } 
} 
public class Teacher 
{ 
public int Id { get; set; } 
public string FirstName { get; set; } 
public string LastName { get; set; } 
6 
} 
public class Subject 
{ 
public int Id { get; set; } 
public string Name { get; set; } 
public int Capacity { get; set; } 
public int TeacherId { get; set; } 
} 

Now, we want to be able to store the data in the database.

The first thing I need to do is to add an Entity Framework to my project.

In Visual Studio, open Nuget Management and search for EntityFramework:

In Visual Studio, open Nuget Management and search for EntityFramework

Another option to install EF is to run the following command in the Package Manager Console:

PM> Install-Package EntityFramework 

Once EF is added to the project and we have our data model, we need to create a Context.

Context defines a session with the database, allowing us to query and save the data.

class FacultyContext : DbContext 
{ 
public DbSet<Student> Students { get; set; } 
public DbSet<Teacher> Teachers { get; set; } 
public DbSet<Subject> Subjects { get; set; } 
} 

Here is a context usage example:

using (var db = new FacultyContext()) 
{ 
var studentsCount = db.Students.Count(); 
db.Students.Add(new Student() 
{ 
FirstName = "Ivan", 
LastName = "Matec", 
Gender = Student.GenderType.Male 
}); 
db.SaveChanges(); 
Assert.AreEqual(studentsCount + 1, db.Students.Count()); 
} 

In this simple example, we have created an instance of FacultyContext and used it to query and add new data to the database.

Use Entity Framework with the SQL Express

Now when we have the data model and database context, let’s connect this context with the local database hosted on SQL express. First, we are adding a database connection string to our app.config.

<connectionStrings> 
<add 
name="FacultyContext" 
connectionString="Data Source=DESKTOP-HPNRP0P\SQLEXPRESS;Initial 
Catalog=FacultyDatabase;Integrated Security=True" 
providerName="System.Data.SqlClient" /> 
</connectionStrings> 

Then we need to add a default constructor to the FacultyContext class.

public FacultyContext() : base("name=FacultyContext") 
{ 
} 

The default constructor calls a base constructor using the name= syntax. It tells Code First that the connection string to use for this context should be loaded from the configuration file. Another option would be setting the database connection string explicitly in the constructor public FacultyContext()

public FacultyContext() 
{ 
this.Database.Connection.ConnectionString = @"Data 
Source=DESKTOP-HPNRP0P\SQLEXPRESS;Initial Catalog=FacultyDatabase;Integrated Security=True"; } 

When we run the application, Code First will do its magic, and the database structure will be created.

Let’s say we want to add a many-to-many relation between Students and Subjects.

Each Student can be assigned to many Subjects, and there can be many Students assigned for each Subject.

Traditionally, we would accomplish it by a cross table with two tables, StudentID and SubjectID. This would define many-to-many connections between the Students and Subjects tables.

In EF, we only need to define a collection navigation property on these classes:

  • For Student, we need to include the navigation property into the collection of Subjects.
  • For Subject, we have to define the navigation property to the collection of Students.

With the default naming convention, EF will create a cross table for us.

public class Student 
{ 
public int Id { get; set; } 
public string FirstName { get; set; } 
public string LastName { get; set; } 
public int BirthYear { get; set; } 
public enum GenderType { Female, Male }; 
public GenderType Gender { get; set; } 
public string Interests { get; set; } 
public virtual ICollection<Subject> Subjects { get; set; } 
} 


public class Subject 
{ 
public int Id { get; set; } 
public string Name { get; set; } 
public int Capacity { get; set; } 
public int TeacherId { get; set; } 
public Teacher Teacher { get; set; } 
public virtual ICollection<Student> Students { get; set; } 
} 

Conclusion

There you have it, an easy way to include and use Entity Framework in your .NET projects. Of course, there is a lot more than is covered in this article. What we can summarize from this short Entity Framework example is how simple and straightforward the Entity Framework is. It does exactly what it needs to do, it handles the database stuff, so we can focus on business logic and higher levels of projects.

As always, thank you for sticking until the end of the article. I hope you enjoyed it and will continue to follow this series on LINQ and related topics.

Tags: , , Last modified: September 16, 2021
Close