logologo
  • Dashboard
  • Features
  • AI Tools
  • FAQs
  • Jobs
  • Modus
logologo

We source, screen & deliver pre-vetted developers—so you only interview high-signal candidates matched to your criteria.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • Pre-Vetted Top Developers

Procodebase © 2025. All rights reserved.

Q: How to work with Entity Framework Core?

author
Generated by
ProCodebase AI

30/10/2024

Entity Framework Core

Introduction to Entity Framework Core

Entity Framework Core is a lightweight, extensible, open-source version of the popular Entity Framework data access technology. It is designed to work with .NET applications, enabling developers to interact with a database using strongly typed C# objects instead of writing raw SQL queries. This approach simplifies data access layers and promotes cleaner code.

Setting Up Your Project

Step 1: Create a New Project

Start by creating a new .NET Core application. You can do this using the .NET CLI (Command Line Interface):

dotnet new console -n MyEFCoreApp

Navigate into your project directory:

cd MyEFCoreApp

Step 2: Add Necessary Packages

To use EF Core, you need to install the relevant NuGet packages. The following command will add EF Core and the SQL Server provider (if you are using SQL Server):

dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 3: Create Your Database Context

The database context acts as a bridge between your domain or entity classes and the database. Create a new class named MyDbContext.cs:

using Microsoft.EntityFrameworkCore; public class MyDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("YourConnectionStringHere"); } }

In this example, we define a DbSet<Product>, which represents the collection of products in the database. Make sure to replace "YourConnectionStringHere" with your actual database connection string.

Step 4: Define Your Entity Class

Next, create a class that represents the data you’ll be working with. For instance, let's create a simple Product class:

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

This Product class represents the items we'll store in our database, with an Id, name, and price.

Working with the Database

Step 5: Create the Database

You can use EF Core Migrations to create the database schema. To do this, first enable migrations:

dotnet ef migrations add InitialCreate

Then, apply the migration to create the database:

dotnet ef database update

This command generates the database based on the model defined in your context and entity classes.

Step 6: Perform CRUD Operations

Create

To add a new product to the database, use the following code in the Main method of your Program.cs:

using (var context = new MyDbContext()) { var product = new Product { Name = "Example Product", Price = 9.99m }; context.Products.Add(product); context.SaveChanges(); }

This code creates a new Product instance, adds it to the Products DbSet, and saves the changes to the database.

Read

To retrieve products from the database:

using (var context = new MyDbContext()) { var products = context.Products.ToList(); foreach (var product in products) { Console.WriteLine($"ID: {product.Id}, Name: {product.Name}, Price: {product.Price}"); } }

Update

To update an existing product:

using (var context = new MyDbContext()) { var product = context.Products.Find(1); // Find by Id if (product != null) { product.Price = 14.99m; context.SaveChanges(); } }

Delete

To remove a product:

using (var context = new MyDbContext()) { var product = context.Products.Find(1); if (product != null) { context.Products.Remove(product); context.SaveChanges(); } }

Best Practices

  • Configuration: Use configuration files to store connection strings and other sensitive information.
  • Use Migrations: Regularly create and apply migrations to keep your database schema in sync with your code.
  • Avoid Over-fetching: Use Include() to load related data as necessary, but avoid loading unnecessary data.

Entity Framework Core provides a straightforward approach to data access in .NET applications, allowing you to concentrate on your application logic rather than the intricacies of SQL. With EF Core, you can efficiently perform CRUD operations, maintain a well-structured data access layer, and leverage the benefits of LINQ when querying your database.

Popular Tags

Entity Framework CoreEF Core.NET

Share now!

Related Questions

  • Write a simple REST API using .NET Core

    30/10/2024 | DotNet

  • What is Kestrel server

    30/10/2024 | DotNet

  • Describe the use of appsettings.json

    30/10/2024 | DotNet

  • How to work with Entity Framework Core

    30/10/2024 | DotNet

  • How to implement custom model binding

    30/10/2024 | DotNet

  • Explain the purpose of the DbContext class

    30/10/2024 | DotNet

  • Describe the differences between .NET Core and .NET Framework

    30/10/2024 | DotNet

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design