Excellent 👏 Sathish — you’ve got your AppDbContext base setup right (it already includes all your key entities ✅).
Now let’s upgrade this file to fully support:
1️⃣ User–Role relationship
2️⃣ Seed data for Roles + Admin User
3️⃣ Future clean architecture compliance
🧩 Updated AppDbContext.cs (Full Version)
📁 Path →
Accounting.Infrastructure/Data/AppDbContext.cs
using Accounting.Core.Entities;
using Microsoft.EntityFrameworkCore;
namespace Accounting.Infrastructure.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
// DbSets (Tables)
public DbSet<Company> Companies { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Vendor> Vendors { get; set; }
public DbSet<Item> Items { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<AuditLog> AuditLogs { get; set; }
// Relationships + Seed Data
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// ✅ Configure 1:N between Role and User
modelBuilder.Entity<User>()
.HasOne(u => u.Role)
.WithMany(r => r.Users)
.HasForeignKey(u => u.RoleId);
// ✅ Optional unique constraints for data integrity
modelBuilder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
// ✅ Seed Roles
modelBuilder.Entity<Role>().HasData(
new Role { Id = 1, Name = "Admin" },
new Role { Id = 2, Name = "User" }
);
// ✅ Seed Admin User
modelBuilder.Entity<User>().HasData(
new User
{
Id = 1,
FullName = "System Administrator",
Email = "admin@company.com",
PasswordHash = "admin@123",
RoleId = 1,
CreatedAtUtc = DateTime.UtcNow
}
);
}
}
}
🧠 Important Notes
✅ You already have User.cs and Role.cs — just make sure:
User.cs
public class User
{
public int Id { get; set; }
public string FullName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PasswordHash { get; set; } = string.Empty;
public int RoleId { get; set; }
public Role? Role { get; set; }
public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
}
Role.cs
public class Role
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public ICollection<User>? Users { get; set; }
}
⚙️ Migration Commands
In terminal (inside your main solution directory):
dotnet ef migrations add AddUserRoleSeed
dotnet ef database update
✅ Verify
In psql:
SELECT * FROM "Roles";
SELECT * FROM "Users";
Expected result:
| Id | Name |
|---|---|
| 1 | Admin |
| 2 | User |
| Id | FullName | RoleId | |
|---|---|---|---|
| 1 | System Administrator | admin@company.com | 1 |
Next Step (📅 Day 4) →
We’ll add Repository usage (UserRepository + RoleRepository),
and build the Controller + Swagger test layer.
Would you like me to start Day 4 (Service + Controller setup) now?
Top comments (0)