Entity Framework Core (EF Core) is an open-source Object-Relational Mapper (ORM) for .NET. It allows developers to work with a database using .NET objects, eliminating the need for most of the data-access code that typically needs to be written. Here’s a step-by-step guide on setting up and using EF Core in a .NET project:
Step 1: Install EF Core
Create a New .NET Project:
dotnet new console -n EFCoreExample
cd EFCoreExample
Add EF Core Package:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Step 2: Define Your Data Model
Create Entity Classes:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Step 3: Create a Database Context
Create DbContext Class:
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionStringHere");
}
}
Step 4: Perform Database Operations
Create a Migration:
dotnet ef migrations add InitialCreate
Update the Database:
dotnet ef database update
Add Data to the Database:
using (var context = new AppDbContext())
{
var product = new Product { Name = "Example Product", Price = 9.99m };
context.Products.Add(product);
context.SaveChanges();
}
Step 5: Query the Database
Retrieve Data:
using (var context = new AppDbContext())
{
var products = context.Products.ToList();
foreach (var product in products)
{
Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
}
}
Example Full Program
Here is a complete example of a console application using EF Core:
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace EFCoreExample
{
public class Product
{
public int ProductId { 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.UseSqlServer("YourConnectionStringHere");
}
}
class Program
{
static void Main(string[] args)
{
using (var context = new AppDbContext())
{
// Add a product
var product = new Product { Name = "Example Product", Price = 9.99m };
context.Products.Add(product);
context.SaveChanges();
// Query products
var products = context.Products.ToList();
foreach (var prod in products)
{
Console.WriteLine($"Name: {prod.Name}, Price: {prod.Price}");
}
}
}
}
}
This should get you started with EF Core in a .NET project. Let me know if you need more details on any specific part!