2080 lines
85 KiB
HTML
2080 lines
85 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="fa" dir="rtl">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>راهنمای پیادهسازی سرویسهای C# با EF Core و SQLite | رویکرد ریپازیتوری</title>
|
||
<style>
|
||
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
||
|
||
:root {
|
||
--primary: #1a365d;
|
||
--primary-light: #2c5282;
|
||
--accent: #c9a961;
|
||
--accent-dark: #a8893f;
|
||
--bg: #faf9f6;
|
||
--card-bg: #ffffff;
|
||
--text: #1a202c;
|
||
--text-muted: #4a5568;
|
||
--border: #e2e8f0;
|
||
--success: #38a169;
|
||
--danger: #e53e3e;
|
||
--warning: #dd6b20;
|
||
--shadow: 0 4px 6px rgba(0,0,0,0.05), 0 10px 30px rgba(26,54,93,0.08);
|
||
}
|
||
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
|
||
body {
|
||
font-family: 'Vazirmatn', Tahoma, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
line-height: 1.9;
|
||
font-size: 15px;
|
||
padding: 30px 15px;
|
||
}
|
||
|
||
.document-container {
|
||
max-width: 950px;
|
||
margin: 0 auto;
|
||
background: var(--card-bg);
|
||
box-shadow: var(--shadow);
|
||
border-radius: 12px;
|
||
overflow: hidden;
|
||
}
|
||
|
||
.document-header {
|
||
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
|
||
color: white;
|
||
padding: 50px 40px 40px;
|
||
position: relative;
|
||
border-bottom: 4px solid var(--accent);
|
||
}
|
||
|
||
.document-header::before {
|
||
content: '';
|
||
position: absolute;
|
||
top: 0; right: 0;
|
||
width: 200px; height: 200px;
|
||
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
|
||
border-radius: 50%;
|
||
transform: translate(50%, -50%);
|
||
}
|
||
|
||
.header-top {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin-bottom: 30px;
|
||
position: relative;
|
||
z-index: 1;
|
||
}
|
||
|
||
.company-badge {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
}
|
||
|
||
.company-logo {
|
||
width: 60px; height: 60px;
|
||
background: var(--accent);
|
||
border-radius: 12px;
|
||
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
|
||
}
|
||
|
||
.doc-meta {
|
||
text-align: left;
|
||
font-size: 12px;
|
||
opacity: 0.9;
|
||
}
|
||
|
||
.doc-meta div { margin-bottom: 3px; }
|
||
|
||
.document-title {
|
||
text-align: center;
|
||
position: relative;
|
||
z-index: 1;
|
||
padding: 20px 0;
|
||
}
|
||
|
||
.document-title .label {
|
||
display: inline-block;
|
||
background: rgba(201,169,97,0.2);
|
||
color: var(--accent);
|
||
padding: 4px 16px;
|
||
border-radius: 20px;
|
||
font-size: 12px;
|
||
font-weight: 600;
|
||
margin-bottom: 15px;
|
||
border: 1px solid rgba(201,169,97,0.4);
|
||
}
|
||
|
||
.document-title h1 {
|
||
font-size: 28px;
|
||
font-weight: 800;
|
||
margin-bottom: 10px;
|
||
letter-spacing: -0.5px;
|
||
}
|
||
|
||
.document-title h2 {
|
||
font-size: 16px;
|
||
font-weight: 400;
|
||
opacity: 0.9;
|
||
}
|
||
|
||
.document-body {
|
||
padding: 40px;
|
||
}
|
||
|
||
.intro-text {
|
||
background: linear-gradient(to left, #f7fafc, #edf2f7);
|
||
border-right: 4px solid var(--accent);
|
||
padding: 20px 25px;
|
||
border-radius: 8px;
|
||
margin-bottom: 35px;
|
||
font-size: 14px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
.section {
|
||
margin-bottom: 40px;
|
||
page-break-inside: avoid;
|
||
}
|
||
|
||
.section-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 15px;
|
||
padding-bottom: 12px;
|
||
border-bottom: 2px solid var(--border);
|
||
margin-bottom: 20px;
|
||
}
|
||
|
||
.section-number {
|
||
width: 50px; height: 50px;
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-radius: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-weight: 800;
|
||
font-size: 20px;
|
||
flex-shrink: 0;
|
||
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
|
||
}
|
||
|
||
.section-title { flex: 1; }
|
||
|
||
.section-title h3 {
|
||
font-size: 19px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 2px;
|
||
}
|
||
|
||
.section-title .subtitle {
|
||
font-size: 12px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
.section-content {
|
||
padding-right: 10px;
|
||
}
|
||
|
||
.section-content p {
|
||
margin-bottom: 12px;
|
||
text-align: justify;
|
||
text-indent: 20px;
|
||
}
|
||
|
||
.section-content p.no-indent { text-indent: 0; }
|
||
|
||
.highlight-box {
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
border: 1px solid #f6e05e;
|
||
border-right: 4px solid var(--accent);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.highlight-box strong { color: var(--accent-dark); }
|
||
|
||
.info-box {
|
||
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
|
||
border: 1px solid #90cdf4;
|
||
border-right: 4px solid var(--primary-light);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.success-box {
|
||
background: linear-gradient(to left, #f0fff4, #e6fffa);
|
||
border: 1px solid #9ae6b4;
|
||
border-right: 4px solid var(--success);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.warning-box {
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
border: 1px solid #fbd38d;
|
||
border-right: 4px solid var(--warning);
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.styled-table {
|
||
width: 100%;
|
||
border-collapse: collapse;
|
||
margin: 20px 0;
|
||
background: white;
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
|
||
}
|
||
|
||
.styled-table thead {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
}
|
||
|
||
.styled-table th {
|
||
padding: 14px 16px;
|
||
text-align: right;
|
||
font-weight: 600;
|
||
font-size: 13px;
|
||
}
|
||
|
||
.styled-table td {
|
||
padding: 13px 16px;
|
||
border-bottom: 1px solid var(--border);
|
||
font-size: 13px;
|
||
}
|
||
|
||
.styled-table tbody tr:last-child td { border-bottom: none; }
|
||
.styled-table tbody tr:nth-child(even) { background: #f8fafc; }
|
||
|
||
.styled-table .highlight-row {
|
||
background: #fffaf0 !important;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.comparison-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 20px;
|
||
margin: 25px 0;
|
||
}
|
||
|
||
.comparison-card {
|
||
background: #f8fafc;
|
||
border: 2px solid var(--border);
|
||
border-radius: 10px;
|
||
padding: 20px;
|
||
position: relative;
|
||
}
|
||
|
||
.comparison-card.recommended {
|
||
border-color: var(--success);
|
||
background: linear-gradient(to left, #f0fff4, #e6fffa);
|
||
}
|
||
|
||
.comparison-card .card-badge {
|
||
position: absolute;
|
||
top: -10px;
|
||
right: 20px;
|
||
background: var(--success);
|
||
color: white;
|
||
padding: 3px 12px;
|
||
border-radius: 15px;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.comparison-card h4 {
|
||
font-size: 16px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 15px;
|
||
padding-bottom: 10px;
|
||
border-bottom: 2px solid var(--border);
|
||
}
|
||
|
||
.comparison-card.recommended h4 { border-bottom-color: var(--success); }
|
||
|
||
.comparison-card ul { list-style: none; padding: 0; }
|
||
|
||
.comparison-card ul li {
|
||
padding: 8px 0;
|
||
border-bottom: 1px solid var(--border);
|
||
font-size: 13px;
|
||
display: flex;
|
||
justify-content: space-between;
|
||
}
|
||
|
||
.comparison-card ul li:last-child { border-bottom: none; }
|
||
|
||
.comparison-card ul li .value {
|
||
font-weight: 600;
|
||
color: var(--primary);
|
||
}
|
||
|
||
.quote-box {
|
||
background: linear-gradient(135deg, #f7fafc, #edf2f7);
|
||
border-right: 4px solid var(--accent);
|
||
padding: 20px 25px;
|
||
border-radius: 8px;
|
||
margin: 20px 0;
|
||
position: relative;
|
||
}
|
||
|
||
.quote-box p {
|
||
font-style: italic;
|
||
color: var(--text-muted);
|
||
margin-bottom: 10px;
|
||
text-indent: 0 !important;
|
||
}
|
||
|
||
.quote-box .source {
|
||
font-size: 12px;
|
||
color: var(--text-muted);
|
||
text-align: left;
|
||
font-style: normal;
|
||
}
|
||
|
||
.stats-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(3, 1fr);
|
||
gap: 15px;
|
||
margin: 25px 0;
|
||
}
|
||
|
||
.stat-card {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 20px;
|
||
border-radius: 10px;
|
||
text-align: center;
|
||
box-shadow: 0 4px 12px rgba(26,54,93,0.2);
|
||
}
|
||
|
||
.stat-card .stat-value {
|
||
font-size: 24px;
|
||
font-weight: 800;
|
||
margin-bottom: 5px;
|
||
color: var(--accent);
|
||
line-height: 1.3;
|
||
}
|
||
|
||
.stat-card .stat-label {
|
||
font-size: 12px;
|
||
opacity: 0.9;
|
||
}
|
||
|
||
.conclusion-box {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 30px;
|
||
border-radius: 12px;
|
||
margin: 30px 0;
|
||
text-align: center;
|
||
box-shadow: 0 8px 20px rgba(26,54,93,0.3);
|
||
}
|
||
|
||
.conclusion-box h3 {
|
||
font-size: 22px;
|
||
font-weight: 800;
|
||
margin-bottom: 15px;
|
||
color: var(--accent);
|
||
}
|
||
|
||
.conclusion-box p {
|
||
font-size: 14px;
|
||
line-height: 1.8;
|
||
text-indent: 0 !important;
|
||
margin-bottom: 15px;
|
||
}
|
||
|
||
.conclusion-box .highlight {
|
||
background: rgba(201,169,97,0.2);
|
||
padding: 15px 20px;
|
||
border-radius: 8px;
|
||
margin-top: 20px;
|
||
border: 1px solid rgba(201,169,97,0.4);
|
||
}
|
||
|
||
.document-footer {
|
||
background: var(--primary);
|
||
color: white;
|
||
padding: 25px 40px;
|
||
text-align: center;
|
||
font-size: 12px;
|
||
margin-top: 40px;
|
||
}
|
||
|
||
.document-footer .footer-brand {
|
||
font-weight: 700;
|
||
color: var(--accent);
|
||
margin-bottom: 5px;
|
||
font-size: 14px;
|
||
}
|
||
|
||
.footer-divider {
|
||
width: 60px;
|
||
height: 2px;
|
||
background: var(--accent);
|
||
margin: 10px auto;
|
||
}
|
||
|
||
.page-info {
|
||
text-align: center;
|
||
padding: 15px;
|
||
font-size: 11px;
|
||
color: var(--text-muted);
|
||
border-top: 1px solid var(--border);
|
||
margin-top: 30px;
|
||
}
|
||
|
||
/* ===== استایلهای افزوده برای بلوکهای کد ===== */
|
||
.code-block {
|
||
background: #1a202c;
|
||
color: #e2e8f0;
|
||
padding: 18px 22px;
|
||
border-radius: 8px;
|
||
overflow-x: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
font-family: 'Consolas', 'Courier New', monospace;
|
||
font-size: 12.5px;
|
||
line-height: 1.75;
|
||
margin: 15px 0;
|
||
border-right: 4px solid var(--accent);
|
||
white-space: pre;
|
||
}
|
||
|
||
.code-block::-webkit-scrollbar { height: 8px; }
|
||
.code-block::-webkit-scrollbar-thumb { background: #4a5568; border-radius: 4px; }
|
||
|
||
.code-label {
|
||
display: inline-block;
|
||
background: #edf2f7;
|
||
color: var(--primary);
|
||
font-family: 'Consolas', monospace;
|
||
font-size: 11.5px;
|
||
padding: 3px 12px;
|
||
border-radius: 6px 6px 0 0;
|
||
margin-bottom: -15px;
|
||
direction: ltr;
|
||
border: 1px solid var(--border);
|
||
border-bottom: none;
|
||
position: relative;
|
||
top: 15px;
|
||
}
|
||
|
||
.inline-code {
|
||
background: #edf2f7;
|
||
color: #c53030;
|
||
padding: 1px 7px;
|
||
border-radius: 4px;
|
||
font-family: 'Consolas', monospace;
|
||
font-size: 12.5px;
|
||
direction: ltr;
|
||
display: inline-block;
|
||
unicode-bidi: embed;
|
||
}
|
||
|
||
.file-tree {
|
||
background: #f8fafc;
|
||
border: 1px solid var(--border);
|
||
border-right: 4px solid var(--primary-light);
|
||
border-radius: 8px;
|
||
padding: 18px 22px;
|
||
font-family: 'Consolas', monospace;
|
||
font-size: 12.5px;
|
||
direction: ltr;
|
||
text-align: left;
|
||
line-height: 2;
|
||
white-space: pre;
|
||
overflow-x: auto;
|
||
margin: 15px 0;
|
||
}
|
||
|
||
.styled-list { padding-right: 20px; margin: 12px 0; }
|
||
.styled-list li { margin-bottom: 8px; font-size: 14px; }
|
||
|
||
.step-list { list-style: none; padding: 0; margin: 15px 0; counter-reset: step; }
|
||
.step-list > li {
|
||
position: relative;
|
||
padding: 12px 55px 12px 15px;
|
||
margin-bottom: 10px;
|
||
background: #f8fafc;
|
||
border: 1px solid var(--border);
|
||
border-radius: 8px;
|
||
font-size: 14px;
|
||
counter-increment: step;
|
||
}
|
||
.step-list > li::before {
|
||
content: counter(step);
|
||
position: absolute;
|
||
right: 12px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
width: 28px; height: 28px;
|
||
background: var(--primary);
|
||
color: white;
|
||
border-radius: 8px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
}
|
||
|
||
@media print {
|
||
body { background: white; padding: 0; }
|
||
.document-container { box-shadow: none; border-radius: 0; }
|
||
.section { page-break-inside: avoid; }
|
||
.code-block { page-break-inside: avoid; }
|
||
}
|
||
|
||
@media (max-width: 768px) {
|
||
.document-body { padding: 25px 20px; }
|
||
.document-header { padding: 30px 20px; }
|
||
.comparison-grid { grid-template-columns: 1fr; }
|
||
.stats-grid { grid-template-columns: 1fr; }
|
||
.header-top { flex-direction: column; gap: 15px; }
|
||
.doc-meta { text-align: center; }
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<div class="document-container">
|
||
|
||
<header class="document-header">
|
||
<div class="header-top">
|
||
<div class="company-badge">
|
||
<div class="company-logo"></div>
|
||
</div>
|
||
<div class="doc-meta">
|
||
<div>شماره مستند: DEV-GUIDE-1405-002</div>
|
||
<div>نسخه: ۱.۰</div>
|
||
<div>تاریخ تهیه: مهر ۱۴۰۵</div>
|
||
<div>طبقهبندی: محرمانه</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="document-title">
|
||
<span class="label">TECHNICAL IMPLEMENTATION GUIDE</span>
|
||
<h1>پیادهسازی سرویسهای C# با Entity Framework Core</h1>
|
||
<h2>الگوی ریپازیتوری + Unit of Work + پایگاه داده SQLite روی مدلهای سامانه</h2>
|
||
</div>
|
||
</header>
|
||
|
||
<div class="document-body">
|
||
|
||
<div class="intro-text">
|
||
<strong>همکار گرامی،</strong><br>
|
||
این مستند یک راهنمای عملی و گامبهگام برای پیادهسازی لایه سرویسهای C# است که بتواند مدلهای موجود در فایل داده (شامل محیطها، محصولات، پروژهها، استقرارها، بردها، ستونها، کارتها و تگها) را با استفاده از Entity Framework Core و رویکرد ریپازیتوری، در پایگاه داده SQLite ذخیره، بازیابی و مدیریت نماید. تمامی کدهای ارائهشده قابل اجرا روی .NET 8 هستند و ساختار پروژه بهگونهای طراحی شده که بهراحتی بتوان Provider را از SQLite به SQL Server یا PostgreSQL تغییر داد.
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۱ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱</div>
|
||
<div class="section-title">
|
||
<h3>معماری کلی و پیشنیازها</h3>
|
||
<div class="subtitle">Architecture Overview & Prerequisites</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>پیش از نوشتن کد، باید لایهبندی پروژه مشخص شود. معماری پیشنهادی چهار لایه دارد و جریان وابستگی همیشه از بیرون به داخل است (لایه ارائه به لایه داده وابسته است، نه برعکس).</p>
|
||
|
||
<table class="styled-table">
|
||
<thead>
|
||
<tr>
|
||
<th>لایه</th>
|
||
<th>مسئولیت</th>
|
||
<th>نمونه کلاسها</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><strong>Domain</strong></td>
|
||
<td>مدلهای موجودیت، قواعد ذاتی دامنه</td>
|
||
<td><span class="inline-code">Product</span> ، <span class="inline-code">Project</span> ، <span class="inline-code">BoardCard</span></td>
|
||
</tr>
|
||
<tr>
|
||
<td><strong>Infrastructure</strong></td>
|
||
<td>DbContext، پیکربندی Fluent API، ریپازیتوریها</td>
|
||
<td><span class="inline-code">AppDbContext</span> ، <span class="inline-code">Repository<T></span></td>
|
||
</tr>
|
||
<tr>
|
||
<td><strong>Application</strong></td>
|
||
<td>سرویسهای کسبوکار، DTO، اعتبارسنجی</td>
|
||
<td><span class="inline-code">ProductService</span> ، <span class="inline-code">BoardService</span></td>
|
||
</tr>
|
||
<tr class="highlight-row">
|
||
<td><strong>Presentation</strong></td>
|
||
<td>Minimal API / Controller، ثبت وابستگیها</td>
|
||
<td><span class="inline-code">Program.cs</span> ، Endpoints</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">بستههای NuGet مورد نیاز:</h4>
|
||
<div class="code-block">dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 8.*
|
||
dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.*
|
||
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 8.* <span style="color:#68d391">// اختیاری (برای Package Manager Console)</span></div>
|
||
|
||
<div class="info-box">
|
||
<strong>💡 نکته:</strong> اگر پروژه از نوع Console است، بهجای <span class="inline-code">Microsoft.AspNetCore.App</span> کافی است بستههای <span class="inline-code">Microsoft.Extensions.DependencyInjection</span> و <span class="inline-code">Microsoft.Extensions.Configuration.Json</span> را نیز اضافه کنید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۲ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۲</div>
|
||
<div class="section-title">
|
||
<h3>ایجاد Solution و ساختار پوشهها</h3>
|
||
<div class="subtitle">Solution & Folder Structure</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>ابتدا Solution و پروژهها را بسازید:</p>
|
||
|
||
<div class="code-block">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</div>
|
||
|
||
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">ساختار نهایی پوشهها:</h4>
|
||
<div class="file-tree">RpkCatalog/
|
||
├── src/
|
||
│ ├── RpkCatalog.Domain/ <span style="color:#718096"># موجودیتها (بدون وابستگی به EF)</span>
|
||
│ │ └── 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</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۳ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۳</div>
|
||
<div class="section-title">
|
||
<h3>طراحی مدلهای دامنه</h3>
|
||
<div class="subtitle">Domain Models</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>مدلها باید دقیقاً بازتاب ساختار فایل JSON باشند. نکات کلیدی طراحی:</p>
|
||
<ul class="styled-list">
|
||
<li>تمام شناسهها از نوع <span class="inline-code">string</span> هستند (مثل <span class="inline-code">env-1789757606914</span>) و بهصورت دستی تولید میشوند؛ بنابراین <span class="inline-code">HasKey</span> صریح لازم است.</li>
|
||
<li>فیلد <span class="inline-code">metadata</span> در محصول و پروژه، ساختار متفاوتی دارد؛ یک نوع مشترک <span class="inline-code">Metadata</span> با فیلدهای nullable این تفاوت را پوشش میدهد.</li>
|
||
<li>آرایههای ساده (مثل <span class="inline-code">dependencies</span> و <span class="inline-code">exploits</span>) که به موجودیت دیگری اشاره میکنند، به جدول واسط تبدیل میشوند تا یکپارچگی ارجاعی حفظ شود.</li>
|
||
<li>آرایههای ساختاریافته و بدون نیاز به کوئری (مثل <span class="inline-code">checklist</span>، <span class="inline-code">assignees</span>، <span class="inline-code">history</span>) بهصورت ستون JSON ذخیره میشوند.</li>
|
||
</ul>
|
||
|
||
<span class="code-label">Models/AppEnvironment.cs · Product.cs · Metadata.cs</span>
|
||
<div class="code-block"><span style="color:#68d391">// ---------- Models/AppEnvironment.cs ----------</span>
|
||
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>();
|
||
}
|
||
|
||
<span style="color:#68d391">// ---------- Models/Metadata.cs ----------</span>
|
||
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();
|
||
}
|
||
|
||
<span style="color:#68d391">// ---------- Models/Product.cs ----------</span>
|
||
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>();
|
||
}</div>
|
||
|
||
<span class="code-label">Models/Project.cs · ProjectDependency.cs · ProjectExploit.cs · Deployment.cs</span>
|
||
<div class="code-block">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; } <span style="color:#68d391">// backend | frontend | database | service | infrastructure</span>
|
||
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>();
|
||
}
|
||
|
||
<span style="color:#68d391">// جدول واسط: این پروژه به کدام پروژهها وابسته است</span>
|
||
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!;
|
||
}
|
||
|
||
<span style="color:#68d391">// جدول واسط: این پروژه از کدام پروژهها استفاده (exploit) میکند</span>
|
||
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();
|
||
}</div>
|
||
|
||
<span class="code-label">Models/Board.cs · BoardColumn.cs · BoardCard.cs · BoardTag.cs</span>
|
||
<div class="code-block">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; } <span style="color:#68d391">// ترتیب ستونها در برد</span>
|
||
|
||
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; }
|
||
|
||
<span style="color:#68d391">// ساختارهای تودرتو بهصورت ستون JSON ذخیره میشوند</span>
|
||
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; }
|
||
}</div>
|
||
|
||
<div class="highlight-box">
|
||
<strong>چرا آرایهها را به JSON تبدیل میکنیم؟</strong> فیلدهایی مانند <span class="inline-code">history</span> یا <span class="inline-code">checklist</span> همیشه همراه کارت خوانده میشوند و هیچگاه بهتنهایی کوئری نمیشوند؛ نگهداشتن آنها در ستون JSON از تعداد جدولها و JOINها میکاهد. اما اگر روزی نیاز شد «همه کارتهای دارای تگ X» را کوئری کنید، بهتر است <span class="inline-code">TagIds</span> را به یک جدول واسط واقعی تبدیل کنید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۴ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۴</div>
|
||
<div class="section-title">
|
||
<h3>پیکربندی EF Core و DbContext</h3>
|
||
<div class="subtitle">DbContext & Fluent API Configuration</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>در این گام، ابتدا یک مبدل عمومی برای ستونهای JSON میسازیم و سپس پیکربندی هر موجودیت را در کلاسهای جداگانه مینویسیم.</p>
|
||
|
||
<span class="code-label">Data/JsonColumnExtensions.cs</span>
|
||
<div class="code-block">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;
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Data/AppDbContext.cs</span>
|
||
<div class="code-block">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)
|
||
{
|
||
<span style="color:#68d391">// همه رشتهها بهصورت TEXT ذخیره میشوند؛ حداکثر طول پیشفرض تعیین میکنیم</span>
|
||
configurationBuilder.Properties<string>().HaveMaxLength(4000);
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Data/Configurations/ProductConfiguration.cs</span>
|
||
<div class="code-block">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);
|
||
|
||
<span style="color:#68d391">// Metadata بهصورت Owned Type در همان جدول Products قرار میگیرد</span>
|
||
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);
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Data/Configurations/ProjectConfiguration.cs</span>
|
||
<div class="code-block">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);
|
||
}
|
||
}
|
||
|
||
<span style="color:#68d391">// ---------- خودارجاعی: وابستگی پروژهها ----------</span>
|
||
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);
|
||
|
||
<span style="color:#68d391">// پروژهای که به آن وابستهایم نباید با حذف این رکورد پاک شود</span>
|
||
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);
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Data/Configurations/DeploymentConfiguration.cs</span>
|
||
<div class="code-block">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);
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Data/Configurations/BoardConfigurations.cs</span>
|
||
<div class="code-block">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);
|
||
}
|
||
}</div>
|
||
|
||
<div class="warning-box">
|
||
<strong>⚠️ نکته مهم درباره SQLite و Owned Type:</strong> اگر یک Owned Type (مثل <span class="inline-code">Metadata</span>) در چند موجودیت استفاده شود و در یک جدول مشترک قرار گیرد، باید نام ستونها را صریحاً تعیین کنید؛ در غیر این صورت EF خطای «ستون تکراری» میدهد. با مشخصکردن <span class="inline-code">HasColumnName</span> برای هر فیلد، این مشکل حل میشود.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۵ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۵</div>
|
||
<div class="section-title">
|
||
<h3>پیادهسازی الگوی ریپازیتوری و Unit of Work</h3>
|
||
<div class="subtitle">Repository Pattern & Unit of Work</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>ریپازیتوری عمومی، عملیات CRUD را یکجا پیادهسازی میکند و ریپازیتوریهای اختصاصی، کوئریهای پیچیدهتر (با <span class="inline-code">Include</span>) را در اختیار سرویسها میگذارند. <span class="inline-code">UnitOfWork</span> نقش یک نقطه دسترسی واحد و مدیریت تراکنش را ایفا میکند.</p>
|
||
|
||
<span class="code-label">Repositories/IRepository.cs</span>
|
||
<div class="code-block">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);
|
||
|
||
<span style="color:#68d391">/// دسترسی به IQueryable برای ساخت کوئریهای ترکیبی و Projection</span>
|
||
IQueryable<TEntity> Query(bool asNoTracking = true);
|
||
}</div>
|
||
|
||
<span class="code-label">Repositories/Repository.cs</span>
|
||
<div class="code-block">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;
|
||
}</div>
|
||
|
||
<span class="code-label">Repositories/IProductRepository.cs + ProductRepository.cs</span>
|
||
<div class="code-block">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() <span style="color:#68d391">// جلوگیری از Cartesian Explosion</span>
|
||
.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);
|
||
}</div>
|
||
|
||
<span class="code-label">Repositories/UnitOfWork.cs</span>
|
||
<div class="code-block">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();
|
||
}</div>
|
||
|
||
<div class="success-box">
|
||
<strong>✓ چرا Unit of Work؟</strong> تمام ریپازیتوریها یک <span class="inline-code">DbContext</span> مشترک دارند؛ بنابراین تغییرات چند موجودیت در یک تراکنش و با یک <span class="inline-code">SaveChangesAsync</span> ذخیره میشوند. این کار هم کارایی را بالا میبرد و هم از ذخیره نیمهکاره داده جلوگیری میکند.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۶ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۶</div>
|
||
<div class="section-title">
|
||
<h3>لایه سرویسها و DTO</h3>
|
||
<div class="subtitle">Application Services & Data Transfer Objects</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>هرگز موجودیتها را مستقیماً به خروجی API ندهید؛ چون روابط دوطرفه باعث خطای <span class="inline-code">A possible object cycle was detected</span> میشود. بهجای آن از DTO و Projection استفاده کنید.</p>
|
||
|
||
<span class="code-label">Dtos/ProductDtos.cs</span>
|
||
<div class="code-block">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);</div>
|
||
|
||
<span class="code-label">Services/IProductService.cs + ProductService.cs</span>
|
||
<div class="code-block">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() <span style="color:#68d391">// AsNoTracking</span>
|
||
.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); <span style="color:#68d391">// Cascade: پروژهها، وابستگیها و استقرارها هم حذف میشوند</span>
|
||
await _uow.SaveChangesAsync(ct);
|
||
return true;
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Services/BoardService.cs — نمونه عملیات دامنهای (جابجایی کارت)</span>
|
||
<div class="code-block">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;
|
||
}
|
||
}</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۷ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۷</div>
|
||
<div class="section-title">
|
||
<h3>ثبت وابستگیها و رشته اتصال</h3>
|
||
<div class="subtitle">Dependency Injection & Connection String</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<span class="code-label">appsettings.json</span>
|
||
<div class="code-block">{
|
||
"ConnectionStrings": {
|
||
"Default": "Data Source=rpk-catalog.db;Cache=Shared;Foreign Keys=True"
|
||
},
|
||
"Logging": {
|
||
"LogLevel": { "Default": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Warning" }
|
||
}
|
||
}</div>
|
||
|
||
<span class="code-label">Program.cs</span>
|
||
<div class="code-block">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();
|
||
|
||
<span style="color:#68d391">// ---------- اعمال مهاجرتها و بارگذاری داده اولیه ----------</span>
|
||
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();
|
||
|
||
<span style="color:#68d391">// ---------- نقاط پایانی نمونه ----------</span>
|
||
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();</div>
|
||
|
||
<div class="info-box">
|
||
<strong>💡 نکته:</strong> اگر پروژه فقط یک سرویس داخلی است و نیازی به API ندارد، همین ثبت وابستگیها را در یک <span class="inline-code">ServiceCollection</span> در پروژه Console تکرار کنید و <span class="inline-code">BuildServiceProvider()</span> را فراخوانی نمایید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۸ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۸</div>
|
||
<div class="section-title">
|
||
<h3>ایجاد مهاجرت و ساخت پایگاه داده</h3>
|
||
<div class="subtitle">Migrations & Database Creation</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>ابزار <span class="inline-code">dotnet-ef</span> را نصب و سپس اولین مهاجرت را ایجاد کنید:</p>
|
||
|
||
<div class="code-block">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</div>
|
||
|
||
<p>پس از اجرا، فایل <span class="inline-code">rpk-catalog.db</span> در پوشه پروژه Api ساخته میشود. جدولهای ایجادشده عبارتاند از:</p>
|
||
|
||
<table class="styled-table">
|
||
<thead>
|
||
<tr>
|
||
<th>جدول</th>
|
||
<th>نقش</th>
|
||
<th>کلید اصلی</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr><td><span class="inline-code">Environments</span></td><td>محیطهای استقرار</td><td>Id (TEXT)</td></tr>
|
||
<tr><td><span class="inline-code">Products</span></td><td>محصولات + Metadata</td><td>Id (TEXT)</td></tr>
|
||
<tr><td><span class="inline-code">Projects</span></td><td>پروژههای هر محصول</td><td>Id (TEXT)</td></tr>
|
||
<tr><td><span class="inline-code">ProjectDependencies</span></td><td>وابستگی بین پروژهها</td><td>مرکب (دو ستون)</td></tr>
|
||
<tr><td><span class="inline-code">ProjectExploits</span></td><td>استفاده از سایر پروژهها</td><td>مرکب (دو ستون)</td></tr>
|
||
<tr><td><span class="inline-code">Deployments</span></td><td>استقرارها</td><td>Id (TEXT)</td></tr>
|
||
<tr><td><span class="inline-code">Boards</span></td><td>بردها</td><td>Id (TEXT)</td></tr>
|
||
<tr><td><span class="inline-code">BoardColumns</span></td><td>ستونهای برد</td><td>Id (TEXT)</td></tr>
|
||
<tr class="highlight-row"><td><span class="inline-code">BoardCards</span></td><td>کارتها + ستونهای JSON</td><td>Id (TEXT)</td></tr>
|
||
<tr><td><span class="inline-code">BoardTags</span></td><td>تگهای برد</td><td>Id (TEXT)</td></tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<div class="warning-box">
|
||
<strong>⚠️ جایگزین سریع برای توسعه:</strong> در فاز توسعه میتوانید بهجای مهاجرت از <span class="inline-code">db.Database.EnsureCreatedAsync()</span> استفاده کنید؛ اما این روش با مهاجرتها سازگار نیست و برای محیط عملیاتی توصیه نمیشود.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۹ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۹</div>
|
||
<div class="section-title">
|
||
<h3>بارگذاری دادههای اولیه از فایل JSON</h3>
|
||
<div class="subtitle">Seeding from the Existing JSON File</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>برای انتقال دادههای فعلی به SQLite، یک Seeder مینویسیم. نکته کلیدی: به دلیل وجود کلید خارجی <span class="inline-code">Restrict</span> روی وابستگیها، باید ابتدا همه پروژهها درج شوند و سپس جدولهای واسط پر شوند.</p>
|
||
|
||
<span class="code-label">Seed/JsonDataSeeder.cs</span>
|
||
<div class="code-block">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; <span style="color:#68d391">// فقط یک بار</span>
|
||
|
||
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);
|
||
|
||
<span style="color:#68d391">// ۱) محیطها</span>
|
||
db.Environments.AddRange(data.Environments.Select(e => new AppEnvironment
|
||
{
|
||
Id = e.Id, Name = e.Name, Description = e.Description,
|
||
BackgroundColor = e.BackgroundColor, TextColor = e.TextColor
|
||
}));
|
||
|
||
<span style="color:#68d391">// ۲) تگهای برد</span>
|
||
db.BoardTags.AddRange(data.BoardTags.Select(t => new BoardTag
|
||
{
|
||
Id = t.Id, Name = t.Name, Color = t.Color
|
||
}));
|
||
|
||
<span style="color:#68d391">// ۳) محصولات، پروژهها و استقرارها</span>
|
||
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);
|
||
}
|
||
|
||
<span style="color:#68d391">// ۴) بردها، ستونها و کارتها</span>
|
||
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);
|
||
}
|
||
|
||
<span style="color:#68d391">// ---------- DTOهای ورودی منطبق بر فایل JSON ----------</span>
|
||
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; }
|
||
}
|
||
}</div>
|
||
|
||
<div class="warning-box">
|
||
<strong>⚠️ نکته ترتیب درج:</strong> چون <span class="inline-code">DependsOnProjectId</span> با <span class="inline-code">DeleteBehavior.Restrict</span> تعریف شده، SQLite اجازه درج وابستگی به پروژهای که هنوز ذخیره نشده را نمیدهد. در کد بالا چون همه پروژهها در یک <span class="inline-code">SaveChangesAsync</span> و در یک تراکنش درج میشوند، EF Core ترتیب صحیح را خودش مدیریت میکند. اگر به خطا خوردید، ابتدا پروژهها را بدون جدول واسط ذخیره کنید و سپس در یک مرحله دوم جدولهای <span class="inline-code">ProjectDependencies</span> و <span class="inline-code">ProjectExploits</span> را پر کنید.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۱۰ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱۰</div>
|
||
<div class="section-title">
|
||
<h3>نمونه کوئریهای کاربردی</h3>
|
||
<div class="subtitle">Common Query Recipes</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>چند سناریوی پرتکرار که در سرویسها به آنها نیاز خواهید داشت:</p>
|
||
|
||
<span class="code-label">۱) پروژههای یک محیط خاص به همراه آخرین استقرار</span>
|
||
<div class="code-block">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);</div>
|
||
|
||
<span class="code-label">۲) یافتن پروژههای بدون استقرار (گلوگاههای انتشار)</span>
|
||
<div class="code-block">var notDeployed = await _uow.Projects.Query()
|
||
.Where(p => !p.Deployments.Any())
|
||
.Select(p => new { p.Id, p.Title, Product = p.Product.Title })
|
||
.ToListAsync(ct);</div>
|
||
|
||
<span class="code-label">۳) نمودار وابستگی یک پروژه (رفت و برگشت)</span>
|
||
<div class="code-block"><span style="color:#68d391">// موادی که این پروژه به آنها وابسته است</span>
|
||
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);
|
||
|
||
<span style="color:#68d391">// پروژههایی که به این پروژه وابستهاند</span>
|
||
var downstream = await _context.ProjectDependencies
|
||
.Where(d => d.DependsOnProjectId == projectId)
|
||
.Select(d => new { d.ProjectId, d.Project.Title })
|
||
.ToListAsync(ct);</div>
|
||
|
||
<span class="code-label">۴) جستوجوی متنی روی کارتهای برد</span>
|
||
<div class="code-block">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);</div>
|
||
|
||
<span class="code-label">۵) بهروزرسانی و حذف انبوه (EF Core 7+)</span>
|
||
<div class="code-block">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);</div>
|
||
|
||
<div class="success-box">
|
||
<strong>✓ مزیت Projection:</strong> در همه نمونههای بالا فقط ستونهای لازم از پایگاه داده خوانده میشوند و موجودیت کامل ردیابی نمیشود؛ نتیجه، مصرف حافظه کمتر و سرعت بالاتر است.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۱۱ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱۱</div>
|
||
<div class="section-title">
|
||
<h3>نکات کارایی و بهترین شیوهها در SQLite</h3>
|
||
<div class="subtitle">Performance & Best Practices</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
|
||
<table class="styled-table">
|
||
<thead>
|
||
<tr>
|
||
<th>موضوع</th>
|
||
<th>توصیه</th>
|
||
<th>دلیل</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td>ردیابی تغییرات</td>
|
||
<td>استفاده از <span class="inline-code">AsNoTracking()</span> در خواندنها</td>
|
||
<td>کاهش مصرف حافظه و افزایش سرعت کوئری</td>
|
||
</tr>
|
||
<tr>
|
||
<td>چند مجموعه تودرتو</td>
|
||
<td>استفاده از <span class="inline-code">AsSplitQuery()</span></td>
|
||
<td>جلوگیری از انفجار کارتزین در JOINها</td>
|
||
</tr>
|
||
<tr>
|
||
<td>تاریخ و زمان</td>
|
||
<td>ذخیره همه تاریخها بهصورت UTC</td>
|
||
<td>SQLite تاریخ را TEXT ذخیره میکند؛ مقایسه و مرتبسازی ISO-8601 درست است</td>
|
||
</tr>
|
||
<tr>
|
||
<td>متن فارسی</td>
|
||
<td>نیازی به پیشوند N نیست</td>
|
||
<td>SQLite همیشه UTF-8 ذخیره میکند</td>
|
||
</tr>
|
||
<tr>
|
||
<td>همزمانی نوشتن</td>
|
||
<td>فعالسازی حالت WAL و کوتاه نگهداشتن تراکنشها</td>
|
||
<td>SQLite فقط یک نویسنده همزمان دارد</td>
|
||
</tr>
|
||
<tr class="highlight-row">
|
||
<td>تعداد ستونهای JSON</td>
|
||
<td>فقط برای دادههای غیرقابلکوئری</td>
|
||
<td>ستون JSON قابل ایندکسگذاری مؤثر نیست</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
|
||
<span class="code-label">فعالسازی WAL در شروع برنامه</span>
|
||
<div class="code-block">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;");
|
||
}</div>
|
||
|
||
<h4 style="margin-top: 25px; color: var(--primary); font-size: 16px;">چکلیست کیفیت کد:</h4>
|
||
<ul class="styled-list">
|
||
<li>هیچگاه موجودیت EF را از لایه سرویس خارج نکنید؛ همیشه DTO برگردانید.</li>
|
||
<li>در متدهای خواندن، <span class="inline-code">CancellationToken</span> را تا انتهای زنجیره منتقل کنید.</li>
|
||
<li>برای هر جدول پرکوئری (مثل <span class="inline-code">Projects.ProductId</span>) ایندکس تعریف کنید.</li>
|
||
<li>عملیات چندمرحلهای را در یک <span class="inline-code">BeginTransactionAsync</span> بپیچید.</li>
|
||
<li>رشتهها و متنهای طولانی را با <span class="inline-code">HasMaxLength</span> محدود کنید تا مدلسازی شفاف باشد.</li>
|
||
<li>از Lazy Loading استفاده نکنید؛ بارگذاری صریح (<span class="inline-code">Include</span>) قابل پیشبینیتر است.</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ===================== بخش ۱۲ ===================== -->
|
||
<div class="section">
|
||
<div class="section-header">
|
||
<div class="section-number">۱۲</div>
|
||
<div class="section-title">
|
||
<h3>جمعبندی و مسیر اجرا</h3>
|
||
<div class="subtitle">Summary & Execution Path</div>
|
||
</div>
|
||
</div>
|
||
<div class="section-content">
|
||
<p>مسیر کامل پیادهسازی در ۸ گام عملیاتی خلاصه میشود:</p>
|
||
|
||
<ol class="step-list">
|
||
<li>ساخت Solution و سه پروژه Domain / Infrastructure / Api و افزودن بستههای EF Core Sqlite و Design.</li>
|
||
<li>تعریف موجودیتهای دامنه مطابق ساختار JSON (محیط، محصول، پروژه، استقرار، برد، ستون، کارت، تگ).</li>
|
||
<li>نوشتن <span class="inline-code">AppDbContext</span>، مبدل JSON و کلاسهای <span class="inline-code">IEntityTypeConfiguration</span>.</li>
|
||
<li>پیادهسازی <span class="inline-code">IRepository<T></span>، ریپازیتوری اختصاصی محصول و <span class="inline-code">UnitOfWork</span>.</li>
|
||
<li>نوشتن سرویسهای کسبوکار و DTOها و استفاده از Projection بهجای بازگرداندن موجودیت.</li>
|
||
<li>ثبت وابستگیها در <span class="inline-code">Program.cs</span> و تنظیم رشته اتصال SQLite.</li>
|
||
<li>اجرای <span class="inline-code">dotnet ef migrations add</span> و <span class="inline-code">database update</span>.</li>
|
||
<li>اجرای Seeder برای انتقال دادههای فایل JSON فعلی و تست نقاط پایانی.</li>
|
||
</ol>
|
||
|
||
<div class="conclusion-box">
|
||
<h3>🎯 نتیجه نهایی</h3>
|
||
<p>با این ساختار، مدلهای فعلی سامانه بهطور کامل و بدون از دست رفتن روابط در SQLite ذخیره میشوند و لایه سرویس شما مستقل از جزئیات پایگاه داده باقی میماند.</p>
|
||
<p>تغییر Provider از SQLite به SQL Server یا PostgreSQL تنها با تغییر یک خط در <span class="inline-code" style="color:#fff; background:rgba(255,255,255,0.15);">Program.cs</span> و نصب بسته مربوطه انجام میشود.</p>
|
||
<div class="highlight">
|
||
<strong>💎 ارزش پیشنهادی:</strong><br>
|
||
جداسازی کامل لایهها + قابلیت تستپذیری بالا + امکان مهاجرت آسان به پایگاه داده سازمانی
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
</div>
|
||
|
||
<footer class="document-footer">
|
||
<div class="footer-brand">RpkCatalog — راهنمای پیادهسازی فنی</div>
|
||
<div class="footer-divider"></div>
|
||
<div>این مستند صرفاً جهت استفاده داخلی تیم فنی ته |