EF Core is a lightweight ORM that allows database operations using C# objects and LINQ.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet Products { get; set; }
}
Manages DB connection and entity tracking.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options) { }
public DbSet Products { get; set; }
}
Query data using C# syntax.
var data = _context.Products
.Where(p => p.Price > 1000)
.ToList();
Non-blocking operations improve performance.
[HttpGet]
public async Task GetProducts()
{
var products = await _context.Products.ToListAsync();
return Ok(products);
}
DTOs are used to transfer only necessary data between layers, improving performance and security.
public class ProductDto
{
public string Name { get; set; }
public decimal Price { get; set; }
}
Maps objects automatically.
CreateMap();
var dto = _mapper.Map(product);
Tracks events and errors.
_logger.LogInformation("Fetched products successfully.");
_logger.LogError("Error fetching products.");
Allows cross-domain API calls.
app.UseCors("AllowAll");
Verifies user identity.
[Authorize]
public IActionResult Secure() => Ok();
Checks user roles/permissions.
[Authorize(Roles="Admin")]
Token-based authentication.
var claims = new[] { new Claim(ClaimTypes.Name, "user") };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret_key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds
);
Supports multiple API versions.
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsController : ControllerBase { }
Fetch data in chunks.
.Skip(0).Take(10)
.Where(p => p.Price > 500)
.OrderBy(p => p.Name)
Separates data access logic.
Unit testing validates individual methods or classes to ensure correctness.
Caching stores frequently used data in memory to improve performance and reduce database load.
var products = _cache.GetOrCreate("products", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return _context.Products.ToList();
});
PUT = full update, PATCH = partial update.
Used to call external APIs.
var client = new HttpClient();
var response = await client.GetStringAsync("https://api.example.com/products");