quotes-net / DbContext /QuoteDbContext.cs
Florin Bobiș
DB mapping issue + new endpoint for random quote
a07d469
raw
history blame
2.63 kB
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class QuoteDbContext : DbContext
{
public DbSet<Quote> Quotes { get; set; }
// Constructor
public QuoteDbContext(DbContextOptions<QuoteDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Configure the Quote entity using Fluent API
modelBuilder.Entity<Quote>(entity =>
{
entity.HasKey(q => q.Id); // Primary key
// Configure indexed columns
entity.HasIndex(q => q.Author);
entity.HasIndex(q => q.QuoteText).IsUnique();
// Column length and constraints are defined using Data Annotations,
// but Fluent API can also be used if needed.
entity.Property(q => q.Author).IsRequired().HasMaxLength(255);
entity.Property(q => q.QuoteText).IsRequired().HasMaxLength(1000);
entity.Property(q => q.Source).HasMaxLength(255);
entity.Property(q => q.Book).HasMaxLength(255);
entity.Property(q => q.Categories).HasMaxLength(255);
entity.Property(q => q.Url).HasMaxLength(500);
entity.Property(q => q.Isbn).HasMaxLength(13);
entity.Property(q => q.Language).HasMaxLength(50);
entity.Property(q => q.OriginalLanguage).HasMaxLength(50);
});
}
}
public class Quote
{
public int Id { get; set; } // Primary key with auto-increment
[Required]
[MaxLength(255)]
public string Author { get; set; } // Indexed column
[Required]
[MaxLength(1000)]
[Column("quote")]
public string QuoteText { get; set; } // Indexed and unique column
[MaxLength(255)]
public string? Source { get; set; } // Nullable column
[MaxLength(255)]
public string? Book { get; set; } // Nullable column
[MaxLength(255)]
public string? Categories { get; set; } // Nullable column
[MaxLength(500)]
public string? Url { get; set; } // Nullable column
[MaxLength(13)]
public string? Isbn { get; set; } // Nullable column
[MaxLength(50)]
public string? Language { get; set; } // Nullable column
[MaxLength(50)]
[Column("original_language")]
public string? OriginalLanguage { get; set; } // Nullable column
[Column("created_at")]
public DateTime DateCreated { get; set; } = DateTime.Now; // Default to current datetime
}