using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public static void Main()
{
using var context = new AppDbContext();
var newStudent = new Student { Name = "John Doe" };
context.Students.Add(newStudent);
context.SaveChanges();
var student = context.Students.First();
Console.WriteLine($"Student ID: {student.Id}, Name: {student.Name}");
}
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public static void Main()
{
using var context = new AppDbContext();
var products = context.Products.Where(p => p.Price > 50).ToList();
foreach (var product in products)
{
Console.WriteLine($"Product ID: {product.Id}, Name: {product.Name}, Price: {product.Price:C}");
}
}
// Define entity class
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
}
// In the application
using var context = new AppDbContext();
context.Database.EnsureCreated(); // Create the database
// Create
var newAuthor = new Author { Name = "J.K. Rowling" };
context.Authors.Add(newAuthor);
context.SaveChanges();
// Read
var author = context.Authors.FirstOrDefault(a => a.Name == "J.K. Rowling");
// Update
if (author != null)
{
author.Name = "Joanne Rowling";
context.SaveChanges();
}
// Delete
if (author != null)
{
context.Authors.Remove(author);
context.SaveChanges();
}
# In the terminal
dotnet ef migrations add InitialCreate
dotnet ef database update
// In an ASP.NET Core Controller
public class AuthorController : ControllerBase
{
private readonly AppDbContext _context;
public AuthorController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public IActionResult GetAuthors()
{
var authors = _context.Authors.ToList();
return Ok(authors);
}
// Implement Create, Update, and Delete actions similarly
}