How to Integrate Entity Framework Core with .NET Console Application Using C# and VSCode
Introduction to Entity Framework Core
In the previous articles, I discussed how to integrate SQLite with a .NET console application using C# and VSCode, and how to use Dapper for data access. You can find those articles at these links: SQLite with .NET Console Application and Using Dapper in .NET Applications.
Now, I’ll show you how simple it is to use Entity Framework Core for data access in your .NET applications. By the end of this tutorial, you’ll understand how to leverage Entity Framework Core to perform efficient and clean database operations with SQLite in your .NET console applications.
What is Entity Framework Core?
Entity Framework (EF) Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), which:
- Enables .NET developers to work with a database using .NET objects.
- Eliminates the need for most of the data-access code that typically needs to be written.
EF Core supports many database engines. See Database Providers for details.
Key Features of Entity Framework Core
EF Core is a modern object-database mapper for .NET with several key features:
- LINQ Queries: EF Core allows you to write database queries using LINQ (Language Integrated Query), which integrates seamlessly with your C# code.
- Change Tracking: EF Core automatically tracks changes made to your entities during the lifespan of a context, so you don’t need to manually manage state.
- Updates: EF Core simplifies the process of updating your database with changes made to your objects.
- Schema Migrations: EF Core supports database migrations, allowing you to evolve your database schema over time without losing data.
- Cross-Database Support: EF Core works with various databases, including SQL Server, Azure SQL Database, SQLite, Azure Cosmos DB, MySQL, and PostgreSQL through a provider plugin API.
Why Use Entity Framework Core?
There are several reasons to consider using Entity Framework Core in your .NET applications:
- Productivity: By reducing the amount of boilerplate code needed for data access, EF Core allows you to focus more on your business logic.
- Maintainability: EF Core’s use of LINQ and C# for queries and updates results in more readable and maintainable code.
- Flexibility: With support for multiple database providers, EF Core can be used in a wide range of applications and environments.
- Performance: EF Core includes performance optimizations and can handle large-scale applications efficiently.
- Community and Support: As an open-source project backed by Microsoft, EF Core has a robust community and extensive documentation, making it easier to find support and resources.
Using Entity Framework Core, you can streamline your data access code and improve the overall architecture of your .NET applications.
Example: Using Entity Framework Core with C# in VSCode
Disclaimer: This example is purely for educational purposes. There are better ways to write code and applications that can optimize this example. Use this as a starting point for learning, but always strive to follow best practices and improve your implementation.
GitHub Repository
All the code related to the use of SQLite, Dapper, and Entity Framework Core is available in this GitHub repository. This repository will help you easily apply the new modifications to the previously created code thanks to the use of tags and branches.
Steps to Integrate Entity Framework Core with a .NET Console Application
- Install the necessary NuGet packages:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Sqlite
- Microsoft.EntityFrameworkCore.Design
- Create the data model:
- Define the context class and entity classes.
- Configure the database context:
- Specify the connection string and configure the context.
- Perform CRUD operations using the context.
Updated Code
Below is the updated code for your console application using Entity Framework Core.
Update the Program.cs
Replace the contents of Program.cs
with the following code. This code uses Entity Framework Core to interact with the SQLite database.
using System; using System.IO; using Microsoft.EntityFrameworkCore; class Program { static void Main(string[] args) { const string databaseFile = "crm.db"; var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlite($"Data Source={databaseFile}") .Options; using (var context = new AppDbContext(options)) { context.Database.EnsureCreated(); CreateTable(context); InsertUsers(context); DisplayAllUsers(context); DeleteUserByName(context, "Otto"); DisplayAllUsers(context); } File.Delete(databaseFile); Console.WriteLine("Database file deleted!"); } private static void DeleteUserByName(AppDbContext context, string name) { var user = context.Users.SingleOrDefault(u => u.Name == name); if (user != null) { context.Users.Remove(user); context.SaveChanges(); Console.WriteLine($"User with name '{name}' deleted."); } } private static void DisplayAllUsers(AppDbContext context) { var users = context.Users; Console.WriteLine("Current users in the database:"); foreach (var user in users) { Console.WriteLine($"ID: {user.Id}, Name: {user.Name}, Age: {user.Age}"); } } private static void InsertUsers(AppDbContext context) { var users = new[] { new User { Name = "Otto", Age = 30 }, new User { Name = "Tim", Age = 25 }, new User { Name = "Steve", Age = 28 }, new User { Name = "Robert", Age = 35 } }; context.Users.AddRange(users); context.SaveChanges(); Console.WriteLine("Users inserted."); } private static void CreateTable(AppDbContext context) { // Table creation is handled by EnsureCreated method Console.WriteLine("Table created."); } } public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<User> Users { get; set; } } public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
Explanation
- AppDbContext Class: This class inherits from
DbContext
and is configured to use SQLite. TheUsers
property represents theUser
table. - User Class: This is the entity class that maps to the
user
table in the database. - Program Class:
- The
Main
method sets up the database connection using Entity Framework. CreateTable
,InsertUsers
,DisplayAllUsers
, andDeleteUserByName
methods perform CRUD operations using EF Core’s context methods.
- The
Run the Application
Compile and run your application to see the results.
dotnet run
You should see the table creation, insertion of users, display of all users, deletion of a user, and the final display of users. The database file will be deleted at the end.
Conclusion
Integrating Entity Framework Core into your .NET console application is straightforward. As demonstrated, updating the previous SQLite code to use Entity Framework Core involved minimal changes, primarily replacing direct SQLite command execution with EF Core’s context and methods. This simplicity allows you to quickly get up and running with EF Core, leveraging its productivity and ease of use.
Overview of Features and Benefits
- Productivity: EF Core reduces the amount of boilerplate code needed for data access, allowing you to focus more on your business logic.
- Maintainability: EF Core’s use of LINQ and C# for queries and updates results in more readable and maintainable code.
- Flexibility: With support for multiple database providers, EF Core can be used in a wide range of applications and environments.
- Performance: EF Core includes performance optimizations and can handle large-scale applications efficiently.
- Schema Migrations: EF Core supports database migrations, allowing you to evolve your database schema over time without losing data.
- Community and Support: As an open-source project backed by Microsoft, EF Core has a robust community and extensive documentation.
Challenges of Entity Framework Core
Despite its many benefits, Entity Framework Core does have some challenges:
- Learning Curve: While EF Core simplifies many aspects of data access, there is a learning curve associated with understanding its conventions and configurations.
- Abstraction Overhead: The abstraction provided by EF Core can sometimes introduce performance overhead compared to direct SQL queries. For performance-critical applications, careful optimization is necessary.
- Complex Queries: Writing very complex queries might require a deep understanding of both LINQ and EF Core’s query translation to SQL, which can be challenging.
Conclusion
Entity Framework Core is an excellent choice for developers who want to combine the control and performance of an ORM with the convenience and productivity features it offers. It strikes a balance between simplicity, performance, and flexibility, making it a valuable tool for many .NET applications.
In the upcoming articles, we will explore how migrations work and demonstrate their power in managing database schemas. We will see how EF Core’s migrations can help you apply changes to your database schema in a controlled and efficient manner, ensuring your application evolves smoothly over time. Stay tuned!
If you think your friends or network would find this article useful, please consider sharing it with them. Your support is greatly appreciated.
Thanks for reading!