شماره مستند: DEV-GUIDE-1405-002
نسخه: ۱.۰
تاریخ تهیه: مهر ۱۴۰۵
طبقه‌بندی: محرمانه
TECHNICAL IMPLEMENTATION GUIDE

پیاده‌سازی سرویس‌های C# با Entity Framework Core

الگوی ریپازیتوری + Unit of Work + پایگاه داده SQLite روی مدل‌های سامانه

همکار گرامی،
این مستند یک راهنمای عملی و گام‌به‌گام برای پیاده‌سازی لایه سرویس‌های C# است که بتواند مدل‌های موجود در فایل داده (شامل محیط‌ها، محصولات، پروژه‌ها، استقرارها، بردها، ستون‌ها، کارت‌ها و تگ‌ها) را با استفاده از Entity Framework Core و رویکرد ریپازیتوری، در پایگاه داده SQLite ذخیره، بازیابی و مدیریت نماید. تمامی کدهای ارائه‌شده قابل اجرا روی .NET 8 هستند و ساختار پروژه به‌گونه‌ای طراحی شده که به‌راحتی بتوان Provider را از SQLite به SQL Server یا PostgreSQL تغییر داد.
۱

معماری کلی و پیش‌نیازها

Architecture Overview & Prerequisites

پیش از نوشتن کد، باید لایه‌بندی پروژه مشخص شود. معماری پیشنهادی چهار لایه دارد و جریان وابستگی همیشه از بیرون به داخل است (لایه ارائه به لایه داده وابسته است، نه برعکس).

لایه مسئولیت نمونه کلاس‌ها
Domain مدل‌های موجودیت، قواعد ذاتی دامنه Product ، Project ، BoardCard
Infrastructure DbContext، پیکربندی Fluent API، ریپازیتوری‌ها AppDbContext ، Repository<T>
Application سرویس‌های کسب‌وکار، DTO، اعتبارسنجی ProductService ، BoardService
Presentation Minimal API / Controller، ثبت وابستگی‌ها Program.cs ، Endpoints

بسته‌های NuGet مورد نیاز:

dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 8.* dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.* dotnet add package Microsoft.EntityFrameworkCore.Tools --version 8.* // اختیاری (برای Package Manager Console)
💡 نکته: اگر پروژه از نوع Console است، به‌جای Microsoft.AspNetCore.App کافی است بسته‌های Microsoft.Extensions.DependencyInjection و Microsoft.Extensions.Configuration.Json را نیز اضافه کنید.
۲

ایجاد Solution و ساختار پوشه‌ها

Solution & Folder Structure

ابتدا Solution و پروژه‌ها را بسازید:

dotnet new sln -n RpkCatalog dotnet new classlib -n RpkCatalog.Domain -o src/RpkCatalog.Domain dotnet new classlib -n RpkCatalog.Infrastructure -o src/RpkCatalog.Infrastructure dotnet new webapi -n RpkCatalog.Api -o src/RpkCatalog.Api dotnet sln add src/RpkCatalog.Domain src/RpkCatalog.Infrastructure src/RpkCatalog.Api dotnet add src/RpkCatalog.Infrastructure reference src/RpkCatalog.Domain dotnet add src/RpkCatalog.Api reference src/RpkCatalog.Infrastructure src/RpkCatalog.Domain

ساختار نهایی پوشه‌ها:

RpkCatalog/ ├── src/ │ ├── RpkCatalog.Domain/ # موجودیت‌ها (بدون وابستگی به EF) │ │ └── Models/ │ │ ├── AppEnvironment.cs │ │ ├── Product.cs │ │ ├── Project.cs │ │ ├── Deployment.cs │ │ ├── Board.cs │ │ └── BoardTag.cs │ │ │ ├── RpkCatalog.Infrastructure/ │ │ ├── Data/ │ │ │ ├── AppDbContext.cs │ │ │ ├── JsonColumnExtensions.cs │ │ │ └── Configurations/ │ │ │ ├── ProductConfiguration.cs │ │ │ ├── ProjectConfiguration.cs │ │ │ └── ... │ │ ├── Repositories/ │ │ │ ├── IRepository.cs │ │ │ ├── Repository.cs │ │ │ ├── IProductRepository.cs │ │ │ ├── ProductRepository.cs │ │ │ └── UnitOfWork.cs │ │ └── Seed/ │ │ └── JsonDataSeeder.cs │ │ │ └── RpkCatalog.Api/ │ ├── Services/ │ │ ├── IProductService.cs │ │ ├── ProductService.cs │ │ └── BoardService.cs │ ├── Dtos/ │ ├── Data/seed.json │ └── Program.cs
۳

طراحی مدل‌های دامنه

Domain Models

مدل‌ها باید دقیقاً بازتاب ساختار فایل JSON باشند. نکات کلیدی طراحی:

  • تمام شناسه‌ها از نوع string هستند (مثل env-1789757606914) و به‌صورت دستی تولید می‌شوند؛ بنابراین HasKey صریح لازم است.
  • فیلد metadata در محصول و پروژه، ساختار متفاوتی دارد؛ یک نوع مشترک Metadata با فیلدهای nullable این تفاوت را پوشش می‌دهد.
  • آرایه‌های ساده (مثل dependencies و exploits) که به موجودیت دیگری اشاره می‌کنند، به جدول واسط تبدیل می‌شوند تا یکپارچگی ارجاعی حفظ شود.
  • آرایه‌های ساختاریافته و بدون نیاز به کوئری (مثل checklist، assignees، history) به‌صورت ستون JSON ذخیره می‌شوند.
Models/AppEnvironment.cs · Product.cs · Metadata.cs
// ---------- Models/AppEnvironment.cs ---------- public class AppEnvironment { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public string? Description { get; set; } public string? BackgroundColor { get; set; } public string? TextColor { get; set; } public ICollection<Deployment> Deployments { get; set; } = new List<Deployment>(); } // ---------- Models/Metadata.cs ---------- public class Metadata { public DateTime CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public string? Owner { get; set; } public string? Framework { get; set; } public string? Language { get; set; } public Dictionary<string, string> CustomFields { get; set; } = new(); } // ---------- Models/Product.cs ---------- public class Product { public string Id { get; set; } = string.Empty; public string Title { get; set; } = string.Empty; public string? Description { get; set; } public Metadata Metadata { get; set; } = new(); public ICollection<Project> Projects { get; set; } = new List<Project>(); }
Models/Project.cs · ProjectDependency.cs · ProjectExploit.cs · Deployment.cs
public class Project { public string Id { get; set; } = string.Empty; public string ProductId { get; set; } = string.Empty; public Product Product { get; set; } = null!; public string Title { get; set; } = string.Empty; public string? Description { get; set; } public string? Type { get; set; } // backend | frontend | database | service | infrastructure public string? RepositoryUrl { get; set; } public Metadata Metadata { get; set; } = new(); public ICollection<ProjectDependency> Dependencies { get; set; } = new List<ProjectDependency>(); public ICollection<ProjectExploit> Exploits { get; set; } = new List<ProjectExploit>(); public ICollection<Deployment> Deployments { get; set; } = new List<Deployment>(); } // جدول واسط: این پروژه به کدام پروژه‌ها وابسته است public class ProjectDependency { public string ProjectId { get; set; } = string.Empty; public string DependsOnProjectId { get; set; } = string.Empty; public Project Project { get; set; } = null!; public Project DependsOnProject { get; set; } = null!; } // جدول واسط: این پروژه از کدام پروژه‌ها استفاده (exploit) می‌کند public class ProjectExploit { public string ProjectId { get; set; } = string.Empty; public string ExploitedProjectId { get; set; } = string.Empty; public Project Project { get; set; } = null!; public Project ExploitedProject { get; set; } = null!; } public class Deployment { public string Id { get; set; } = string.Empty; public string ProjectId { get; set; } = string.Empty; public Project Project { get; set; } = null!; public string EnvironmentId { get; set; } = string.Empty; public AppEnvironment Environment { get; set; } = null!; public string? Version { get; set; } public DateTime DeploymentDate { get; set; } public string? ReleaseNotes { get; set; } public string? Url { get; set; } public string Status { get; set; } = "active"; public List<string> RequiredDeployments { get; set; } = new(); public List<string> RequiredExploits { get; set; } = new(); }
Models/Board.cs · BoardColumn.cs · BoardCard.cs · BoardTag.cs
public class Board { public string Id { get; set; } = string.Empty; public string Title { get; set; } = string.Empty; public string? Description { get; set; } public string? BackgroundColor { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } public ICollection<BoardColumn> Columns { get; set; } = new List<BoardColumn>(); } public class BoardColumn { public string Id { get; set; } = string.Empty; public string BoardId { get; set; } = string.Empty; public Board Board { get; set; } = null!; public string Title { get; set; } = string.Empty; public string? BackgroundColor { get; set; } public string? TextColor { get; set; } public int Order { get; set; } // ترتیب ستون‌ها در برد public ICollection<BoardCard> Cards { get; set; } = new List<BoardCard>(); } public class BoardCard { public string Id { get; set; } = string.Empty; public string ColumnId { get; set; } = string.Empty; public BoardColumn Column { get; set; } = null!; public string Title { get; set; } = string.Empty; public string? Description { get; set; } public DateTime? EstimatedDate { get; set; } public string? BackgroundColor { get; set; } // ساختارهای تودرتو به‌صورت ستون JSON ذخیره می‌شوند public List<string> TagIds { get; set; } = new(); public List<ChecklistItem> Checklist { get; set; } = new(); public List<Assignee> Assignees { get; set; } = new(); public List<string> DependencyCardIds { get; set; } = new(); public List<CardHistoryItem> History { get; set; } = new(); public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } } public class ChecklistItem { public string Id { get; set; } = string.Empty; public string Text { get; set; } = string.Empty; public bool IsDone { get; set; } } public class Assignee { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; } public class CardHistoryItem { public string? Type { get; set; } public string? Title { get; set; } public string? From { get; set; } public string? To { get; set; } public DateTime Date { get; set; } } public class BoardTag { public string Id { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public string? Color { get; set; } }
چرا آرایه‌ها را به JSON تبدیل می‌کنیم؟ فیلدهایی مانند history یا checklist همیشه همراه کارت خوانده می‌شوند و هیچ‌گاه به‌تنهایی کوئری نمی‌شوند؛ نگه‌داشتن آن‌ها در ستون JSON از تعداد جدول‌ها و JOIN‌ها می‌کاهد. اما اگر روزی نیاز شد «همه کارت‌های دارای تگ X» را کوئری کنید، بهتر است TagIds را به یک جدول واسط واقعی تبدیل کنید.
۴

پیکربندی EF Core و DbContext

DbContext & Fluent API Configuration

در این گام، ابتدا یک مبدل عمومی برای ستون‌های JSON می‌سازیم و سپس پیکربندی هر موجودیت را در کلاس‌های جداگانه می‌نویسیم.

Data/JsonColumnExtensions.cs
using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; public static class JsonColumnExtensions { private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web); public static PropertyBuilder<T> HasJsonColumn<T>(this PropertyBuilder<T> builder) where T : class, new() { var converter = new ValueConverter<T, string>( v => JsonSerializer.Serialize(v, Options), v => string.IsNullOrWhiteSpace(v) ? new T() : (JsonSerializer.Deserialize<T>(v, Options) ?? new T())); var comparer = new ValueComparer<T>( (a, b) => JsonSerializer.Serialize(a, Options) == JsonSerializer.Serialize(b, Options), v => JsonSerializer.Serialize(v, Options).GetHashCode(), v => JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(v, Options), Options)!); builder.HasConversion(converter); builder.Metadata.SetValueComparer(comparer); return builder; } }
Data/AppDbContext.cs
using Microsoft.EntityFrameworkCore; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<AppEnvironment> Environments => Set<AppEnvironment>(); public DbSet<Product> Products => Set<Product>(); public DbSet<Project> Projects => Set<Project>(); public DbSet<ProjectDependency> ProjectDependencies => Set<ProjectDependency>(); public DbSet<ProjectExploit> ProjectExploits => Set<ProjectExploit>(); public DbSet<Deployment> Deployments => Set<Deployment>(); public DbSet<Board> Boards => Set<Board>(); public DbSet<BoardColumn> BoardColumns => Set<BoardColumn>(); public DbSet<BoardCard> BoardCards => Set<BoardCard>(); public DbSet<BoardTag> BoardTags => Set<BoardTag>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); } protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { // همه رشته‌ها به‌صورت TEXT ذخیره می‌شوند؛ حداکثر طول پیش‌فرض تعیین می‌کنیم configurationBuilder.Properties<string>().HaveMaxLength(4000); } }
Data/Configurations/ProductConfiguration.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class ProductConfiguration : IEntityTypeConfiguration<Product> { public void Configure(EntityTypeBuilder<Product> b) { b.ToTable("Products"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Title).HasMaxLength(300).IsRequired(); b.Property(x => x.Description).HasMaxLength(2000); // Metadata به‌صورت Owned Type در همان جدول Products قرار می‌گیرد b.OwnsOne(x => x.Metadata, m => { m.Property(p => p.CreatedAt).HasColumnName("CreatedAt"); m.Property(p => p.UpdatedAt).HasColumnName("UpdatedAt"); m.Property(p => p.Owner).HasColumnName("Owner").HasMaxLength(200); m.Property(p => p.Framework).HasColumnName("Framework").HasMaxLength(100); m.Property(p => p.Language).HasColumnName("Language").HasMaxLength(100); m.Property(p => p.CustomFields) .HasColumnName("CustomFields") .HasJsonColumn(); }); b.HasMany(x => x.Projects) .WithOne(x => x.Product) .HasForeignKey(x => x.ProductId) .OnDelete(DeleteBehavior.Cascade); } }
Data/Configurations/ProjectConfiguration.cs
public class ProjectConfiguration : IEntityTypeConfiguration<Project> { public void Configure(EntityTypeBuilder<Project> b) { b.ToTable("Projects"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Title).HasMaxLength(300).IsRequired(); b.Property(x => x.Type).HasMaxLength(50); b.Property(x => x.RepositoryUrl).HasMaxLength(1000); b.OwnsOne(x => x.Metadata, m => { m.Property(p => p.CreatedAt).HasColumnName("CreatedAt"); m.Property(p => p.UpdatedAt).HasColumnName("UpdatedAt"); m.Property(p => p.Owner).HasColumnName("Owner").HasMaxLength(200); m.Property(p => p.Framework).HasColumnName("Framework").HasMaxLength(100); m.Property(p => p.Language).HasColumnName("Language").HasMaxLength(100); m.Property(p => p.CustomFields).HasColumnName("CustomFields").HasJsonColumn(); }); b.HasIndex(x => x.ProductId); b.HasIndex(x => x.Type); } } // ---------- خودارجاعی: وابستگی پروژه‌ها ---------- public class ProjectDependencyConfiguration : IEntityTypeConfiguration<ProjectDependency> { public void Configure(EntityTypeBuilder<ProjectDependency> b) { b.ToTable("ProjectDependencies"); b.HasKey(x => new { x.ProjectId, x.DependsOnProjectId }); b.HasOne(x => x.Project) .WithMany(p => p.Dependencies) .HasForeignKey(x => x.ProjectId) .OnDelete(DeleteBehavior.Cascade); // پروژه‌ای که به آن وابسته‌ایم نباید با حذف این رکورد پاک شود b.HasOne(x => x.DependsOnProject) .WithMany() .HasForeignKey(x => x.DependsOnProjectId) .OnDelete(DeleteBehavior.Restrict); } } public class ProjectExploitConfiguration : IEntityTypeConfiguration<ProjectExploit> { public void Configure(EntityTypeBuilder<ProjectExploit> b) { b.ToTable("ProjectExploits"); b.HasKey(x => new { x.ProjectId, x.ExploitedProjectId }); b.HasOne(x => x.Project).WithMany(p => p.Exploits) .HasForeignKey(x => x.ProjectId).OnDelete(DeleteBehavior.Cascade); b.HasOne(x => x.ExploitedProject).WithMany() .HasForeignKey(x => x.ExploitedProjectId).OnDelete(DeleteBehavior.Restrict); } }
Data/Configurations/DeploymentConfiguration.cs
public class DeploymentConfiguration : IEntityTypeConfiguration<Deployment> { public void Configure(EntityTypeBuilder<Deployment> b) { b.ToTable("Deployments"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Version).HasMaxLength(50); b.Property(x => x.Status).HasMaxLength(50); b.Property(x => x.Url).HasMaxLength(1000); b.Property(x => x.ReleaseNotes).HasMaxLength(4000); b.Property(x => x.RequiredDeployments).HasJsonColumn(); b.Property(x => x.RequiredExploits).HasJsonColumn(); b.HasOne(x => x.Project).WithMany(p => p.Deployments) .HasForeignKey(x => x.ProjectId).OnDelete(DeleteBehavior.Cascade); b.HasOne(x => x.Environment).WithMany(e => e.Deployments) .HasForeignKey(x => x.EnvironmentId).OnDelete(DeleteBehavior.Restrict); b.HasIndex(x => x.ProjectId); b.HasIndex(x => new { x.EnvironmentId, x.Status }); b.HasIndex(x => x.DeploymentDate); } }
Data/Configurations/BoardConfigurations.cs
public class BoardConfiguration : IEntityTypeConfiguration<Board> { public void Configure(EntityTypeBuilder<Board> b) { b.ToTable("Boards"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Title).HasMaxLength(300).IsRequired(); b.Property(x => x.BackgroundColor).HasMaxLength(16); b.HasMany(x => x.Columns) .WithOne(x => x.Board) .HasForeignKey(x => x.BoardId) .OnDelete(DeleteBehavior.Cascade); } } public class BoardColumnConfiguration : IEntityTypeConfiguration<BoardColumn> { public void Configure(EntityTypeBuilder<BoardColumn> b) { b.ToTable("BoardColumns"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Title).HasMaxLength(200).IsRequired(); b.HasMany(x => x.Cards) .WithOne(x => x.Column) .HasForeignKey(x => x.ColumnId) .OnDelete(DeleteBehavior.Cascade); b.HasIndex(x => new { x.BoardId, x.Order }); } } public class BoardCardConfiguration : IEntityTypeConfiguration<BoardCard> { public void Configure(EntityTypeBuilder<BoardCard> b) { b.ToTable("BoardCards"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Title).HasMaxLength(300).IsRequired(); b.Property(x => x.Description).HasMaxLength(4000); b.Property(x => x.TagIds).HasJsonColumn(); b.Property(x => x.Checklist).HasJsonColumn(); b.Property(x => x.Assignees).HasJsonColumn(); b.Property(x => x.DependencyCardIds).HasJsonColumn(); b.Property(x => x.History).HasJsonColumn(); b.HasIndex(x => x.ColumnId); b.HasIndex(x => x.UpdatedAt); } } public class BoardTagConfiguration : IEntityTypeConfiguration<BoardTag> { public void Configure(EntityTypeBuilder<BoardTag> b) { b.ToTable("BoardTags"); b.HasKey(x => x.Id); b.Property(x => x.Id).HasMaxLength(64); b.Property(x => x.Name).HasMaxLength(100).IsRequired(); b.Property(x => x.Color).HasMaxLength(16); } }
⚠️ نکته مهم درباره SQLite و Owned Type: اگر یک Owned Type (مثل Metadata) در چند موجودیت استفاده شود و در یک جدول مشترک قرار گیرد، باید نام ستون‌ها را صریحاً تعیین کنید؛ در غیر این صورت EF خطای «ستون تکراری» می‌دهد. با مشخص‌کردن HasColumnName برای هر فیلد، این مشکل حل می‌شود.
۵

پیاده‌سازی الگوی ریپازیتوری و Unit of Work

Repository Pattern & Unit of Work

ریپازیتوری عمومی، عملیات CRUD را یک‌جا پیاده‌سازی می‌کند و ریپازیتوری‌های اختصاصی، کوئری‌های پیچیده‌تر (با Include) را در اختیار سرویس‌ها می‌گذارند. UnitOfWork نقش یک نقطه دسترسی واحد و مدیریت تراکنش را ایفا می‌کند.

Repositories/IRepository.cs
using System.Linq.Expressions; public interface IRepository<TEntity> where TEntity : class { Task<TEntity?> GetByIdAsync(string id, CancellationToken ct = default); Task<IReadOnlyList<TEntity>> GetAllAsync(CancellationToken ct = default); Task<IReadOnlyList<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken ct = default); Task<bool> AnyAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken ct = default); Task<int> CountAsync(Expression<Func<TEntity, bool>>? predicate = null, CancellationToken ct = default); Task AddAsync(TEntity entity, CancellationToken ct = default); Task AddRangeAsync(IEnumerable<TEntity> entities, CancellationToken ct = default); void Update(TEntity entity); void Remove(TEntity entity); /// دسترسی به IQueryable برای ساخت کوئری‌های ترکیبی و Projection IQueryable<TEntity> Query(bool asNoTracking = true); }
Repositories/Repository.cs
using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; public class Repository<TEntity> : IRepository<TEntity> where TEntity : class { protected readonly AppDbContext Context; protected readonly DbSet<TEntity> Set; public Repository(AppDbContext context) { Context = context; Set = context.Set<TEntity>(); } public async Task<TEntity?> GetByIdAsync(string id, CancellationToken ct = default) => await Set.FindAsync(new object?[] { id }, ct); public async Task<IReadOnlyList<TEntity>> GetAllAsync(CancellationToken ct = default) => await Set.AsNoTracking().ToListAsync(ct); public async Task<IReadOnlyList<TEntity>> FindAsync( Expression<Func<TEntity, bool>> predicate, CancellationToken ct = default) => await Set.AsNoTracking().Where(predicate).ToListAsync(ct); public Task<bool> AnyAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken ct = default) => Set.AnyAsync(predicate, ct); public Task<int> CountAsync(Expression<Func<TEntity, bool>>? predicate = null, CancellationToken ct = default) => predicate is null ? Set.CountAsync(ct) : Set.CountAsync(predicate, ct); public async Task AddAsync(TEntity entity, CancellationToken ct = default) => await Set.AddAsync(entity, ct); public async Task AddRangeAsync(IEnumerable<TEntity> entities, CancellationToken ct = default) => await Set.AddRangeAsync(entities, ct); public void Update(TEntity entity) => Set.Update(entity); public void Remove(TEntity entity) => Set.Remove(entity); public IQueryable<TEntity> Query(bool asNoTracking = true) => asNoTracking ? Set.AsNoTracking() : Set; }
Repositories/IProductRepository.cs + ProductRepository.cs
public interface IProductRepository : IRepository<Product> { Task<Product?> GetWithProjectsAsync(string id, CancellationToken ct = default); Task<IReadOnlyList<Product>> GetAllWithProjectsAsync(CancellationToken ct = default); } public class ProductRepository : Repository<Product>, IProductRepository { public ProductRepository(AppDbContext context) : base(context) { } public Task<Product?> GetWithProjectsAsync(string id, CancellationToken ct = default) => Context.Products .AsNoTracking() .AsSplitQuery() // جلوگیری از Cartesian Explosion .Include(p => p.Projects) .ThenInclude(pr => pr.Dependencies) .Include(p => p.Projects) .ThenInclude(pr => pr.Exploits) .Include(p => p.Projects) .ThenInclude(pr => pr.Deployments) .FirstOrDefaultAsync(p => p.Id == id, ct); public async Task<IReadOnlyList<Product>> GetAllWithProjectsAsync(CancellationToken ct = default) => await Context.Products .AsNoTracking() .AsSplitQuery() .Include(p => p.Projects) .OrderBy(p => p.Title) .ToListAsync(ct); }
Repositories/UnitOfWork.cs
using Microsoft.EntityFrameworkCore.Storage; public interface IUnitOfWork : IAsyncDisposable { IRepository<AppEnvironment> Environments { get; } IProductRepository Products { get; } IRepository<Project> Projects { get; } IRepository<Deployment> Deployments { get; } IRepository<Board> Boards { get; } IRepository<BoardColumn> Columns { get; } IRepository<BoardCard> Cards { get; } IRepository<BoardTag> Tags { get; } Task<int> SaveChangesAsync(CancellationToken ct = default); Task<IDbContextTransaction> BeginTransactionAsync(CancellationToken ct = default); } public class UnitOfWork : IUnitOfWork { private readonly AppDbContext _context; public UnitOfWork(AppDbContext context) { _context = context; Environments = new Repository<AppEnvironment>(context); Products = new ProductRepository(context); Projects = new Repository<Project>(context); Deployments = new Repository<Deployment>(context); Boards = new Repository<Board>(context); Columns = new Repository<BoardColumn>(context); Cards = new Repository<BoardCard>(context); Tags = new Repository<BoardTag>(context); } public IRepository<AppEnvironment> Environments { get; } public IProductRepository Products { get; } public IRepository<Project> Projects { get; } public IRepository<Deployment> Deployments { get; } public IRepository<Board> Boards { get; } public IRepository<BoardColumn> Columns { get; } public IRepository<BoardCard> Cards { get; } public IRepository<BoardTag> Tags { get; } public Task<int> SaveChangesAsync(CancellationToken ct = default) => _context.SaveChangesAsync(ct); public Task<IDbContextTransaction> BeginTransactionAsync(CancellationToken ct = default) => _context.Database.BeginTransactionAsync(ct); public ValueTask DisposeAsync() => _context.DisposeAsync(); }
✓ چرا Unit of Work؟ تمام ریپازیتوری‌ها یک DbContext مشترک دارند؛ بنابراین تغییرات چند موجودیت در یک تراکنش و با یک SaveChangesAsync ذخیره می‌شوند. این کار هم کارایی را بالا می‌برد و هم از ذخیره نیمه‌کاره داده جلوگیری می‌کند.
۶

لایه سرویس‌ها و DTO

Application Services & Data Transfer Objects

هرگز موجودیت‌ها را مستقیماً به خروجی API ندهید؛ چون روابط دوطرفه باعث خطای A possible object cycle was detected می‌شود. به‌جای آن از DTO و Projection استفاده کنید.

Dtos/ProductDtos.cs
public record ProductSummaryDto( string Id, string Title, string? Description, string? Owner, int ProjectCount); public record ProjectDto( string Id, string Title, string? Type, string? RepositoryUrl, string? Framework, List<string> Dependencies, List<string> Exploits, int DeploymentCount); public record ProductDetailDto( string Id, string Title, string? Description, string? Owner, DateTime CreatedAt, List<ProjectDto> Projects); public record CreateProductDto(string Title, string? Description, string? Owner); public record UpdateProductDto(string Title, string? Description, string? Owner);
Services/IProductService.cs + ProductService.cs
public interface IProductService { Task<IReadOnlyList<ProductSummaryDto>> GetAllAsync(CancellationToken ct = default); Task<ProductDetailDto?> GetAsync(string id, CancellationToken ct = default); Task<string> CreateAsync(CreateProductDto dto, CancellationToken ct = default); Task<bool> UpdateAsync(string id, UpdateProductDto dto, CancellationToken ct = default); Task<bool> DeleteAsync(string id, CancellationToken ct = default); } public class ProductService : IProductService { private readonly IUnitOfWork _uow; public ProductService(IUnitOfWork uow) => _uow = uow; public async Task<IReadOnlyList<ProductSummaryDto>> GetAllAsync(CancellationToken ct = default) => await _uow.Products.Query() // AsNoTracking .OrderBy(p => p.Title) .Select(p => new ProductSummaryDto( p.Id, p.Title, p.Description, p.Metadata.Owner, p.Projects.Count)) .ToListAsync(ct); public async Task<ProductDetailDto?> GetAsync(string id, CancellationToken ct = default) => await _uow.Products.Query() .Where(p => p.Id == id) .Select(p => new ProductDetailDto( p.Id, p.Title, p.Description, p.Metadata.Owner, p.Metadata.CreatedAt, p.Projects.Select(pr => new ProjectDto( pr.Id, pr.Title, pr.Type, pr.RepositoryUrl, pr.Metadata.Framework, pr.Dependencies.Select(d => d.DependsOnProjectId).ToList(), pr.Exploits.Select(e => e.ExploitedProjectId).ToList(), pr.Deployments.Count)).ToList())) .FirstOrDefaultAsync(ct); public async Task<string> CreateAsync(CreateProductDto dto, CancellationToken ct = default) { var product = new Product { Id = $"prod-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", Title = dto.Title, Description = dto.Description, Metadata = new Metadata { CreatedAt = DateTime.UtcNow, Owner = dto.Owner, CustomFields = new Dictionary<string, string>() } }; await _uow.Products.AddAsync(product, ct); await _uow.SaveChangesAsync(ct); return product.Id; } public async Task<bool> UpdateAsync(string id, UpdateProductDto dto, CancellationToken ct = default) { var product = await _uow.Products.GetByIdAsync(id, ct); if (product is null) return false; product.Title = dto.Title; product.Description = dto.Description; product.Metadata.Owner = dto.Owner; product.Metadata.UpdatedAt = DateTime.UtcNow; _uow.Products.Update(product); await _uow.SaveChangesAsync(ct); return true; } public async Task<bool> DeleteAsync(string id, CancellationToken ct = default) { var product = await _uow.Products.GetByIdAsync(id, ct); if (product is null) return false; _uow.Products.Remove(product); // Cascade: پروژه‌ها، وابستگی‌ها و استقرارها هم حذف می‌شوند await _uow.SaveChangesAsync(ct); return true; } }
Services/BoardService.cs — نمونه عملیات دامنه‌ای (جابجایی کارت)
public interface IBoardService { Task<Board?> GetBoardAsync(string boardId, CancellationToken ct = default); Task<bool> MoveCardAsync(string cardId, string targetColumnId, CancellationToken ct = default); Task<string> CreateCardAsync(string columnId, string title, string? description, CancellationToken ct = default); } public class BoardService : IBoardService { private readonly IUnitOfWork _uow; public BoardService(IUnitOfWork uow) => _uow = uow; public Task<Board?> GetBoardAsync(string boardId, CancellationToken ct = default) => _uow.Boards.Query() .AsSplitQuery() .Include(b => b.Columns.OrderBy(c => c.Order)) .ThenInclude(c => c.Cards) .FirstOrDefaultAsync(b => b.Id == boardId, ct); public async Task<bool> MoveCardAsync(string cardId, string targetColumnId, CancellationToken ct = default) { var card = await _uow.Cards.GetByIdAsync(cardId, ct); if (card is null) return false; var targetColumn = await _uow.Columns.GetByIdAsync(targetColumnId, ct); if (targetColumn is null || targetColumn.BoardId != card.Column.BoardId) return false; var fromTitle = card.Column?.Title ?? "—"; card.ColumnId = targetColumnId; card.UpdatedAt = DateTime.UtcNow; card.History.Add(new CardHistoryItem { Type = "move", Title = $"جابجایی به \"{targetColumn.Title}\"", From = fromTitle, To = targetColumn.Title, Date = DateTime.UtcNow }); _uow.Cards.Update(card); await _uow.SaveChangesAsync(ct); return true; } public async Task<string> CreateCardAsync(string columnId, string title, string? description, CancellationToken ct = default) { var card = new BoardCard { Id = $"card-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", ColumnId = columnId, Title = title, Description = description, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; card.History.Add(new CardHistoryItem { Type = "create", Title = "ایجاد کارت", From = "—", To = "ستون مقصد", Date = DateTime.UtcNow }); await _uow.Cards.AddAsync(card, ct); await _uow.SaveChangesAsync(ct); return card.Id; } }
۷

ثبت وابستگی‌ها و رشته اتصال

Dependency Injection & Connection String
appsettings.json
{ "ConnectionStrings": { "Default": "Data Source=rpk-catalog.db;Cache=Shared;Foreign Keys=True" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Warning" } } }
Program.cs
using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("Default"), sqlite => sqlite.CommandTimeout(30))); builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); builder.Services.AddScoped<IProductRepository, ProductRepository>(); builder.Services.AddScoped<IUnitOfWork, UnitOfWork>(); builder.Services.AddScoped<IProductService, ProductService>(); builder.Services.AddScoped<IBoardService, BoardService>(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // ---------- اعمال مهاجرت‌ها و بارگذاری داده اولیه ---------- using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); await db.Database.MigrateAsync(); await JsonDataSeeder.SeedAsync(db, Path.Combine(app.Environment.ContentRootPath, "Data", "seed.json")); } app.UseSwagger(); app.UseSwaggerUI(); // ---------- نقاط پایانی نمونه ---------- app.MapGet("/api/products", async (IProductService svc, CancellationToken ct) => Results.Ok(await svc.GetAllAsync(ct))); app.MapGet("/api/products/{id}", async (string id, IProductService svc, CancellationToken ct) => await svc.GetAsync(id, ct) is { } dto ? Results.Ok(dto) : Results.NotFound()); app.MapPost("/api/products", async (CreateProductDto dto, IProductService svc, CancellationToken ct) => Results.Created($"/api/products/{await svc.CreateAsync(dto, ct)}", null)); app.MapPut("/api/products/{id}", async (string id, UpdateProductDto dto, IProductService svc, CancellationToken ct) => await svc.UpdateAsync(id, dto, ct) ? Results.NoContent() : Results.NotFound()); app.MapDelete("/api/products/{id}", async (string id, IProductService svc, CancellationToken ct) => await svc.DeleteAsync(id, ct) ? Results.NoContent() : Results.NotFound()); app.MapGet("/api/boards/{id}", async (string id, IBoardService svc, CancellationToken ct) => await svc.GetBoardAsync(id, ct) is { } board ? Results.Ok(board) : Results.NotFound()); app.Run();
💡 نکته: اگر پروژه فقط یک سرویس داخلی است و نیازی به API ندارد، همین ثبت وابستگی‌ها را در یک ServiceCollection در پروژه Console تکرار کنید و BuildServiceProvider() را فراخوانی نمایید.
۸

ایجاد مهاجرت و ساخت پایگاه داده

Migrations & Database Creation

ابزار dotnet-ef را نصب و سپس اولین مهاجرت را ایجاد کنید:

dotnet tool install --global dotnet-ef --version 8.* dotnet ef migrations add InitialCreate --project src/RpkCatalog.Infrastructure --startup-project src/RpkCatalog.Api dotnet ef database update --project src/RpkCatalog.Infrastructure --startup-project src/RpkCatalog.Api

پس از اجرا، فایل rpk-catalog.db در پوشه پروژه Api ساخته می‌شود. جدول‌های ایجادشده عبارت‌اند از:

جدول نقش کلید اصلی
Environmentsمحیط‌های استقرارId (TEXT)
Productsمحصولات + MetadataId (TEXT)
Projectsپروژه‌های هر محصولId (TEXT)
ProjectDependenciesوابستگی بین پروژه‌هامرکب (دو ستون)
ProjectExploitsاستفاده از سایر پروژه‌هامرکب (دو ستون)
DeploymentsاستقرارهاId (TEXT)
BoardsبردهاId (TEXT)
BoardColumnsستون‌های بردId (TEXT)
BoardCardsکارت‌ها + ستون‌های JSONId (TEXT)
BoardTagsتگ‌های بردId (TEXT)
⚠️ جایگزین سریع برای توسعه: در فاز توسعه می‌توانید به‌جای مهاجرت از db.Database.EnsureCreatedAsync() استفاده کنید؛ اما این روش با مهاجرت‌ها سازگار نیست و برای محیط عملیاتی توصیه نمی‌شود.
۹

بارگذاری داده‌های اولیه از فایل JSON

Seeding from the Existing JSON File

برای انتقال داده‌های فعلی به SQLite، یک Seeder می‌نویسیم. نکته کلیدی: به دلیل وجود کلید خارجی Restrict روی وابستگی‌ها، باید ابتدا همه پروژه‌ها درج شوند و سپس جدول‌های واسط پر شوند.

Seed/JsonDataSeeder.cs
using System.Text.Json; using Microsoft.EntityFrameworkCore; public static class JsonDataSeeder { private static readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; public static async Task SeedAsync(AppDbContext db, string jsonPath, CancellationToken ct = default) { if (!File.Exists(jsonPath)) return; if (await db.Products.AnyAsync(ct)) return; // فقط یک بار var json = await File.ReadAllTextAsync(jsonPath, ct); var data = JsonSerializer.Deserialize<DataFile>(json, Options); if (data is null) return; await using var tx = await db.Database.BeginTransactionAsync(ct); // ۱) محیط‌ها db.Environments.AddRange(data.Environments.Select(e => new AppEnvironment { Id = e.Id, Name = e.Name, Description = e.Description, BackgroundColor = e.BackgroundColor, TextColor = e.TextColor })); // ۲) تگ‌های برد db.BoardTags.AddRange(data.BoardTags.Select(t => new BoardTag { Id = t.Id, Name = t.Name, Color = t.Color })); // ۳) محصولات، پروژه‌ها و استقرارها foreach (var p in data.Products) { var product = new Product { Id = p.Id, Title = p.Title, Description = p.Description, Metadata = new Metadata { CreatedAt = p.Metadata?.CreatedAt ?? DateTime.UtcNow, UpdatedAt = p.Metadata?.UpdatedAt, Owner = p.Metadata?.Owner, CustomFields = p.Metadata?.CustomFields ?? new() } }; foreach (var pr in p.Projects) { var project = new Project { Id = pr.Id, ProductId = p.Id, Title = pr.Title, Description = pr.Description, Type = pr.Type, RepositoryUrl = pr.RepositoryUrl, Metadata = new Metadata { CreatedAt = pr.Metadata?.CreatedAt ?? DateTime.UtcNow, UpdatedAt = pr.Metadata?.UpdatedAt, Owner = pr.Metadata?.Owner, Framework = pr.Metadata?.Framework, Language = pr.Metadata?.Language, CustomFields = pr.Metadata?.CustomFields ?? new() }, Dependencies = pr.Dependencies .Select(d => new ProjectDependency { ProjectId = pr.Id, DependsOnProjectId = d }) .ToList(), Exploits = pr.Exploits .Select(e => new ProjectExploit { ProjectId = pr.Id, ExploitedProjectId = e }) .ToList() }; foreach (var dep in pr.Deployments) { project.Deployments.Add(new Deployment { Id = dep.Id, ProjectId = pr.Id, EnvironmentId = dep.EnvironmentId, Version = dep.Version, DeploymentDate = dep.DeploymentDate, ReleaseNotes = dep.ReleaseNotes, Url = dep.Url, Status = dep.Status ?? "active", RequiredDeployments = dep.RequiredDeployments ?? new(), RequiredExploits = dep.RequiredExploits ?? new() }); } product.Projects.Add(project); } db.Products.Add(product); } // ۴) بردها، ستون‌ها و کارت‌ها foreach (var b in data.Boards) { var board = new Board { Id = b.Id, Title = b.Title, Description = b.Description, BackgroundColor = b.BackgroundColor, CreatedAt = b.CreatedAt, UpdatedAt = b.UpdatedAt }; var order = 0; foreach (var col in b.Columns) { var column = new BoardColumn { Id = col.Id, BoardId = b.Id, Title = col.Title, BackgroundColor = col.BackgroundColor, TextColor = col.TextColor, Order = order++ }; foreach (var c in col.Cards) { column.Cards.Add(new BoardCard { Id = c.Id, ColumnId = col.Id, Title = c.Title, Description = c.Description, EstimatedDate = c.EstimatedDate, BackgroundColor = c.BackgroundColor, TagIds = c.Tags ?? new(), Checklist = c.Checklist ?? new(), Assignees = c.Assignees ?? new(), DependencyCardIds = c.Dependencies ?? new(), History = c.History ?? new(), CreatedAt = c.CreatedAt, UpdatedAt = c.UpdatedAt }); } board.Columns.Add(column); } db.Boards.Add(board); } await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); } // ---------- DTOهای ورودی منطبق بر فایل JSON ---------- private class DataFile { public List<EnvDto> Environments { get; set; } = new(); public List<ProductDto> Products { get; set; } = new(); public List<BoardDto> Boards { get; set; } = new(); public List<TagDto> BoardTags { get; set; } = new(); } private class EnvDto { public string Id { get; set; } = ""; public string Name { get; set; } = ""; public string? Description { get; set; } public string? BackgroundColor { get; set; } public string? TextColor { get; set; } } private class ProductDto { public string Id { get; set; } = ""; public string Title { get; set; } = ""; public string? Description { get; set; } public MetaDto? Metadata { get; set; } public List<ProjectDto> Projects { get; set; } = new(); } private class ProjectDto { public string Id { get; set; } = ""; public string Title { get; set; } = ""; public string? Description { get; set; } public string? Type { get; set; } public string? RepositoryUrl { get; set; } public MetaDto? Metadata { get; set; } public List<string> Dependencies { get; set; } = new(); public List<string> Exploits { get; set; } = new(); public List<DeploymentDto> Deployments { get; set; } = new(); } private class DeploymentDto { public string Id { get; set; } = ""; public string EnvironmentId { get; set; } = ""; public string? Version { get; set; } public DateTime DeploymentDate { get; set; } public string? ReleaseNotes { get; set; } public string? Url { get; set; } public List<string>? RequiredDeployments { get; set; } public List<string>? RequiredExploits { get; set; } public string? Status { get; set; } } private class MetaDto { public DateTime? CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public string? Owner { get; set; } public string? Framework { get; set; } public string? Language { get; set; } public Dictionary<string, string>? CustomFields { get; set; } } private class BoardDto { public string Id { get; set; } = ""; public string Title { get; set; } = ""; public string? Description { get; set; } public string? BackgroundColor { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } public List<ColumnDto> Columns { get; set; } = new(); } private class ColumnDto { public string Id { get; set; } = ""; public string Title { get; set; } = ""; public string? BackgroundColor { get; set; } public string? TextColor { get; set; } public List<CardDto> Cards { get; set; } = new(); } private class CardDto { public string Id { get; set; } = ""; public string Title { get; set; } = ""; public string? Description { get; set; } public DateTime? EstimatedDate { get; set; } public string? BackgroundColor { get; set; } public List<string>? Tags { get; set; } public List<ChecklistItem>? Checklist { get; set; } public List<Assignee>? Assignees { get; set; } public List<string>? Dependencies { get; set; } public List<CardHistoryItem>? History { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } } private class TagDto { public string Id { get; set; } = ""; public string Name { get; set; } = ""; public string? Color { get; set; } } }
⚠️ نکته ترتیب درج: چون DependsOnProjectId با DeleteBehavior.Restrict تعریف شده، SQLite اجازه درج وابستگی به پروژه‌ای که هنوز ذخیره نشده را نمی‌دهد. در کد بالا چون همه پروژه‌ها در یک SaveChangesAsync و در یک تراکنش درج می‌شوند، EF Core ترتیب صحیح را خودش مدیریت می‌کند. اگر به خطا خوردید، ابتدا پروژه‌ها را بدون جدول واسط ذخیره کنید و سپس در یک مرحله دوم جدول‌های ProjectDependencies و ProjectExploits را پر کنید.
۱۰

نمونه کوئری‌های کاربردی

Common Query Recipes

چند سناریوی پرتکرار که در سرویس‌ها به آن‌ها نیاز خواهید داشت:

۱) پروژه‌های یک محیط خاص به همراه آخرین استقرار
var projects = await _uow.Projects.Query() .Where(p => p.Deployments.Any(d => d.EnvironmentId == envId && d.Status == "active")) .Select(p => new { p.Id, p.Title, LastDeployment = p.Deployments .Where(d => d.EnvironmentId == envId) .OrderByDescending(d => d.DeploymentDate) .Select(d => new { d.Version, d.DeploymentDate, d.Url }) .FirstOrDefault() }) .ToListAsync(ct);
۲) یافتن پروژه‌های بدون استقرار (گلوگاه‌های انتشار)
var notDeployed = await _uow.Projects.Query() .Where(p => !p.Deployments.Any()) .Select(p => new { p.Id, p.Title, Product = p.Product.Title }) .ToListAsync(ct);
۳) نمودار وابستگی یک پروژه (رفت و برگشت)
// موادی که این پروژه به آن‌ها وابسته است var upstream = await _uow.Projects.Query() .Where(p => p.Id == projectId) .SelectMany(p => p.Dependencies) .Select(d => new { d.DependsOnProjectId, d.DependsOnProject.Title }) .ToListAsync(ct); // پروژه‌هایی که به این پروژه وابسته‌اند var downstream = await _context.ProjectDependencies .Where(d => d.DependsOnProjectId == projectId) .Select(d => new { d.ProjectId, d.Project.Title }) .ToListAsync(ct);
۴) جست‌وجوی متنی روی کارت‌های برد
var cards = await _uow.Cards.Query() .Where(c => EF.Functions.Like(c.Title, $"%{term}%") || EF.Functions.Like(c.Description, $"%{term}%")) .OrderByDescending(c => c.UpdatedAt) .Take(50) .Select(c => new { c.Id, c.Title, Column = c.Column.Title, Board = c.Column.Board.Title }) .ToListAsync(ct);
۵) به‌روزرسانی و حذف انبوه (EF Core 7+)
await _context.Deployments .Where(d => d.EnvironmentId == envId && d.Status == "active") .ExecuteUpdateAsync(s => s.SetProperty(d => d.Status, "archived"), ct); await _context.BoardCards .Where(c => c.UpdatedAt < DateTime.UtcNow.AddYears(-2)) .ExecuteDeleteAsync(ct);
✓ مزیت Projection: در همه نمونه‌های بالا فقط ستون‌های لازم از پایگاه داده خوانده می‌شوند و موجودیت کامل ردیابی نمی‌شود؛ نتیجه، مصرف حافظه کمتر و سرعت بالاتر است.
۱۱

نکات کارایی و بهترین شیوه‌ها در SQLite

Performance & Best Practices
موضوع توصیه دلیل
ردیابی تغییرات استفاده از AsNoTracking() در خواندن‌ها کاهش مصرف حافظه و افزایش سرعت کوئری
چند مجموعه تودرتو استفاده از AsSplitQuery() جلوگیری از انفجار کارتزین در JOIN‌ها
تاریخ و زمان ذخیره همه تاریخ‌ها به‌صورت UTC SQLite تاریخ را TEXT ذخیره می‌کند؛ مقایسه و مرتب‌سازی ISO-8601 درست است
متن فارسی نیازی به پیشوند N نیست SQLite همیشه UTF-8 ذخیره می‌کند
همزمانی نوشتن فعال‌سازی حالت WAL و کوتاه نگه‌داشتن تراکنش‌ها SQLite فقط یک نویسنده همزمان دارد
تعداد ستون‌های JSON فقط برای داده‌های غیرقابل‌کوئری ستون JSON قابل ایندکس‌گذاری مؤثر نیست
فعال‌سازی WAL در شروع برنامه
using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); await db.Database.MigrateAsync(); await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL;"); await db.Database.ExecuteSqlRawAsync("PRAGMA synchronous=NORMAL;"); await db.Database.ExecuteSqlRawAsync("PRAGMA busy_timeout=5000;"); }

چک‌لیست کیفیت کد:

  • هیچ‌گاه موجودیت EF را از لایه سرویس خارج نکنید؛ همیشه DTO برگردانید.
  • در متدهای خواندن، CancellationToken را تا انتهای زنجیره منتقل کنید.
  • برای هر جدول پرکوئری (مثل Projects.ProductId) ایندکس تعریف کنید.
  • عملیات چندمرحله‌ای را در یک BeginTransactionAsync بپیچید.
  • رشته‌ها و متن‌های طولانی را با HasMaxLength محدود کنید تا مدل‌سازی شفاف باشد.
  • از Lazy Loading استفاده نکنید؛ بارگذاری صریح (Include) قابل پیش‌بینی‌تر است.
۱۲

جمع‌بندی و مسیر اجرا

Summary & Execution Path

مسیر کامل پیاده‌سازی در ۸ گام عملیاتی خلاصه می‌شود:

  1. ساخت Solution و سه پروژه Domain / Infrastructure / Api و افزودن بسته‌های EF Core Sqlite و Design.
  2. تعریف موجودیت‌های دامنه مطابق ساختار JSON (محیط، محصول، پروژه، استقرار، برد، ستون، کارت، تگ).
  3. نوشتن AppDbContext، مبدل JSON و کلاس‌های IEntityTypeConfiguration.
  4. پیاده‌سازی IRepository<T>، ریپازیتوری اختصاصی محصول و UnitOfWork.
  5. نوشتن سرویس‌های کسب‌وکار و DTOها و استفاده از Projection به‌جای بازگرداندن موجودیت.
  6. ثبت وابستگی‌ها در Program.cs و تنظیم رشته اتصال SQLite.
  7. اجرای dotnet ef migrations add و database update.
  8. اجرای Seeder برای انتقال داده‌های فایل JSON فعلی و تست نقاط پایانی.

🎯 نتیجه نهایی

با این ساختار، مدل‌های فعلی سامانه به‌طور کامل و بدون از دست رفتن روابط در SQLite ذخیره می‌شوند و لایه سرویس شما مستقل از جزئیات پایگاه داده باقی می‌ماند.

تغییر Provider از SQLite به SQL Server یا PostgreSQL تنها با تغییر یک خط در Program.cs و نصب بسته مربوطه انجام می‌شود.

💎 ارزش پیشنهادی:
جداسازی کامل لایه‌ها + قابلیت تست‌پذیری بالا + امکان مهاجرت آسان به پایگاه داده سازمانی