using Microsoft.EntityFrameworkCore; using ComiServ.Entities; namespace ComiServ; public class ComicsContext : DbContext { //TODO is this the best place for this to live? public const int HANDLE_LENGTH = 12; //relies on low probability of repeat handles in a short period of time //duplicate handles could be created before either of them are commited public string CreateHandle() { char ToChar(int i) { if (i < 10) return (char)('0' + i); if (i - 10 + 'A' < 'O') return (char)('A' + i - 10); else //skip 'O' return (char)('A' + i - 9); } string handle = ""; do { handle = string.Join("", Enumerable.Repeat(0, HANDLE_LENGTH) .Select(_ => ToChar(Random.Shared.Next(0, 35)))); } while (Comics.Any(c => c.Handle == handle)); return handle; } public DbSet Comics { get; set; } public DbSet ComicTags { get; set; } public DbSet Tags { get; set; } public DbSet ComicAuthors { get; set; } public DbSet Authors { get; set; } public DbSet Covers { get; set; } public DbSet Users { get; set; } public DbSet UserTypes { get; set; } public DbSet ComicsRead { get; set; } public ComicsContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().ToTable("Comics"); modelBuilder.Entity().ToTable("ComicTags"); modelBuilder.Entity().ToTable("Tags"); modelBuilder.Entity().ToTable("ComicAuthors"); modelBuilder.Entity().ToTable("Authors"); modelBuilder.Entity().ToTable("Covers"); modelBuilder.Entity().ToTable("Users"); modelBuilder.Entity().ToTable("UserTypes") .HasData( Enum.GetValues(typeof(UserTypeEnum)) .Cast() .Select(e => new UserType() { Id = e, Name = e.ToString() }) ); } /// /// puts a user-provided handle into the proper form /// /// /// formatted handle or null if invalid public static string? CleanValidateHandle(string? handle) { if (handle is null) return null; handle = handle.Trim(); if (handle.Length != HANDLE_LENGTH) return null; return handle.ToUpper(); } }