DEV Community

Juarez Júnior
Juarez Júnior

Posted on

Mapping and Manipulating Data with Entity Framework Core

Entity Framework Core (EF Core) is an ORM (Object-Relational Mapper) that makes interacting with relational databases directly through C# code easier. It allows you to map domain classes to database tables and perform operations like CRUD (Create, Read, Update, Delete) efficiently and easily. In this example, we will see how to configure a context class and perform an insert operation in a SQLite database.

Libraries:
To use Entity Framework Core with support for SQLite, install the following NuGet packages in your project:

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Sqlite
Enter fullscreen mode Exit fullscreen mode

Example Code:

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace EntityFrameworkCoreExample
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=products.db");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                context.Database.EnsureCreated();

                // Inserting a new product
                context.Products.Add(new Product { Name = "Laptop", Price = 1500.99m });
                context.SaveChanges();

                // Fetching and displaying the products from the database
                var products = context.Products.ToList();
                foreach (var product in products)
                {
                    Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:
In this example, we create the Product class with the properties Id, Name, and Price. Then, we configure the AppDbContext class, which represents the database context, and use the UseSqlite method to indicate that the database will be SQLite. In the Main method, we ensure the database is created and insert a new product into the table. After that, we fetch all the products from the database and display them in the console.

Conclusion:
Entity Framework Core simplifies the development of applications that interact with databases, allowing you to manipulate data directly through C# classes without needing to write SQL manually. It supports a wide range of databases and is a powerful tool for building robust systems.

Source code: GitHub

Top comments (0)