Files
Finlytic/FinlyticNews/Database/NewsDbContext.cs
T

71 lines
2.5 KiB
C#

using FinlyticNews.Entities;
using Microsoft.EntityFrameworkCore;
namespace FinlyticNews.Database;
/// <summary>
/// Entity Framework Core database context for the news microservice,
/// managing article sources, processed news, and matched assets.
/// </summary>
public class NewsDbContext : DbContext
{
/// <summary>
/// Initializes a new instance of the <see cref="NewsDbContext"/> class.
/// </summary>
/// <param name="options">The context configuration options.</param>
public NewsDbContext(DbContextOptions<NewsDbContext> options) : base(options)
{
}
/// <summary>
/// Gets or sets the database set for configured article sources.
/// </summary>
public DbSet<ArticleSourceEntity> ArticleSources => Set<ArticleSourceEntity>();
/// <summary>
/// Gets or sets the database set for news articles.
/// </summary>
public DbSet<NewsArticleEntity> NewsArticles => Set<NewsArticleEntity>();
/// <summary>
/// Gets or sets the database set for matched assets.
/// </summary>
public DbSet<MatchedAssetEntity> MatchedAssets => Set<MatchedAssetEntity>();
/// <summary>
/// Gets or sets the database set for microservice configuration settings.
/// </summary>
public DbSet<NewsSettingsEntity> Settings => Set<NewsSettingsEntity>();
/// <summary>
/// Configures the model mapping, database constraints, and unique indices.
/// </summary>
/// <param name="modelBuilder">The builder being used to construct the database schema model.</param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Configure unique index on SourceUrl for deduplication check (idempotency)
modelBuilder.Entity<NewsArticleEntity>()
.HasIndex(a => a.SourceUrl)
.IsUnique();
// Performance indexes for news queries
modelBuilder.Entity<NewsArticleEntity>()
.HasIndex(a => new { a.PublishedAt, a.ScrapedAt });
modelBuilder.Entity<NewsArticleEntity>()
.HasIndex(a => a.Status);
modelBuilder.Entity<MatchedAssetEntity>()
.HasIndex(m => m.Isin);
// Configure relationship between NewsArticle and MatchedAssets
modelBuilder.Entity<MatchedAssetEntity>()
.HasOne(m => m.NewsArticle)
.WithMany(a => a.MatchedAssets)
.HasForeignKey(m => m.NewsArticleId)
.OnDelete(DeleteBehavior.Cascade);
}
}