3. Data Models & DTOs
- Data Models & DTOs
3.1 Creating Domain Models
namespace CommandAPI.Models;public class Platform{ [Key] public int Id { get; set; } [Required] public required string PlatformName { get; set; } // Navigation property public ICollection
// ❌ WRONG (current code has this issue)public class AppDbContext : DbContext{ public DbSet
public class PlatformMutateDto{ [Required(ErrorMessage = “Platform name is required”)] [MaxLength(100, ErrorMessage = “Platform name cannot exceed 100 characters”)] [MinLength(2, ErrorMessage = “Platform name must be at least 2 characters”)] public required string PlatformName { get; init; }}public class CommandMutateDto{ [Required] [MaxLength(250)] public required string HowTo { get; init; } [Required] public required string CommandLine { get; init; } [Range(1, int.MaxValue, ErrorMessage = “Valid Platform ID required”)] public int PlatformId { get; set; }} Common Annotations: [Required] - non-null, non-empty [MaxLength(n)] - string/array length [Range(min, max)] - numeric bounds [EmailAddress], [Url], [Phone] - format validation [RegularExpression(pattern)] - custom patterns 3.5 The Separation of Concerns Principle
┌─────────────────┐ ┌──────────────┐ ┌────────────────┐│ Controller │────▶│ Repository │────▶│ DbContext ││ (HTTP Logic) │ │ (Data Logic) │ │ (EF Core) │└─────────────────┘ └──────────────┘ └────────────────┘ │ │ ▼ ▼ ┌─────────┐ ┌──────────┐ │ DTO │ │ Models │ └─────────┘ └──────────┘ │ │ └────────────────┬─────────────────────────────┘ ▼ ┌────────────┐ │ AutoMapper │ └────────────┘ Layers Explained: Controller: Handles HTTP, validates input, returns responses Repository: Data access logic, queries, business rules DbContext: EF Core abstraction over database Models: Database entities DTOs: API contracts AutoMapper: Transforms between Models and DTOs