To get started with Entity Framework, we need to add the necessary NuGet packages to the project. Follow these steps:
Create a Project:
Install NuGet Package:
Microsoft.EntityFrameworkCore
and install it.Install-Package Microsoft.EntityFrameworkCore
Database Connection:
DbContext
class.First, we need to define a model class and a DbContext
class.
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=EFTestDb;Trusted_Connection=True;");
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
To add a new product to the database, we use the Add
method. Here's an example:
public static void CreateProduct()
{
using (var context = new ApplicationDbContext())
{
var product = new Product
{
Name = "Laptop",
Price = 1500.00M
};
context.Products.Add(product);
context.SaveChanges();
}
}
To read data from the database, we can use methods like Find
or FirstOrDefault
.
public static void ReadProduct(int productId)
{
using (var context = new ApplicationDbContext())
{
var product = context.Products.FirstOrDefault(p => p.Id == productId);
if (product != null)
{
Console.WriteLine($"Product ID: {product.Id}, Name: {product.Name}, Price: {product.Price}");
}
else
{
Console.WriteLine("Product not found.");
}
}
}
The FirstOrDefault method retrieves the first entity that matches the specified condition. If no entity is found, it returns null
.
To update an existing record, we retrieve it and change its properties.
public static void UpdateProduct(int productId, string newName, decimal newPrice)
{
using (var context = new ApplicationDbContext())
{
var product = context.Products.FirstOrDefault(p => p.Id == productId);
if (product != null)
{
product.Name = newName;
product.Price = newPrice;
context.SaveChanges();
}
}
}
To delete a product, we use the Remove
method.
public static void DeleteProduct(int productId)
{
using (var context = new ApplicationDbContext())
{
var product = context.Products.FirstOrDefault(p => p.Id == productId);
if (product != null)
{
context.Products.Remove(product);
context.SaveChanges();
}
}
}
These examples demonstrate how to perform basic database operations with EF. You can explore more advanced features like handling related tables, managing transactions, and using LINQ queries for complex operations.
If you have any questions or need further assistance, feel free to ask!