C# .NET Repository Pattern & BAL Generator for VS CodeAn enterprise-grade Visual Studio Code extension that automates the generation of production-ready Repository Pattern, BAL Pattern (Business Access Layer), Data-Annotated Models, and Controllers (MVC View, Ajax JSON, Kendo UI) for C# and ASP.NET Core / MVC projects. Generate domain Models, contracts (Interfaces), concrete Repositories, direct BAL Helpers, and Controllers in seconds via right-click folder context menus or the Command Palette. 🌟 Why Developers Love This Extension
🏗️ Architecture Styles: Repository vs. BALChoose the pattern that matches your project architecture:
Directory ArchitectureRepository Pattern Layout
BAL Pattern Layout
🚀 Quick Start & UsageMethod 1: Right-Click Context Menu (Recommended)
Method 2: Command Palette
📋 Interactive Guided WizardWhen generating code, the extension guides you through an intuitive, multi-step flow:
🔒 Role-Based Authorization IntegrationThe extension supports role-based security tailored for both Razor Views and JSON APIs / Ajax: 1. Role-Based for MVC Razor ViewsUsed for server-rendered HTML pages where unauthorized users should be redirected:
2. Role-Based for Ajax / JSON APIsUsed for SPA / client-side Ajax calls where unauthorized requests return standard JSON and HTTP 403 status:
🔑 Session & Authentication Setup (
|
| Trigger Prefix | Description | Generated Code Preview |
|---|---|---|
prop_key, pk_prop |
Primary Key with [Key] |
[Key][DatabaseGenerated(Identity)] public int Id { get; set; } |
prop_email, email |
Email with [EmailAddress][Required] |
[Required][EmailAddress][MaxLength(256)] public string EmailAddress { get; set; } |
prop_phone, phone |
Phone number with [Phone] |
[Required][Phone][MaxLength(20)] public string PhoneNumber { get; set; } |
prop_password, password |
Password with length rules | [Required][MinLength(8)][MaxLength(128)][DataType(DataType.Password)] public string Password { get; set; } |
prop_compare, confirmpassword |
ConfirmPassword with [Compare] |
[Required][Compare("Password")] public string ConfirmPassword { get; set; } |
prop_username, username |
Username validation | [Required][MinLength(3)][MaxLength(100)] public string UserName { get; set; } |
prop_fullname, fullname |
Full Name | [Required][MaxLength(150)] public string FullName { get; set; } |
prop_date, dateonly |
Modern safe DateOnly |
[Required] public DateOnly EventDate { get; set; } |
prop_time, timeonly |
TimeSpan / TimeOnly |
[Required] public TimeSpan EventTime { get; set; } |
prop_gender, gender |
Gender with regex constraint | [Required][RegularExpression(@"^(Male\|Female\|Other)$")] public string Gender { get; set; } |
prop_price, price |
Currency with [Range] |
[Required][Range(0.01, double.MaxValue)][Column(TypeName="decimal(18,2)")] public decimal Price { get; set; } |
prop_seats, quantity |
Seats / Positive integer | [Required][Range(1, int.MaxValue)] public int TotalSeats { get; set; } |
prop_isactive, status |
Active status boolean flag | public bool IsActive { get; set; } = true; |
prop_url, imageurl |
URL with [Url] attribute |
[Url][MaxLength(2000)] public string ImageUrl { get; set; } |
prop_role, role |
User role with regex | [Required][MaxLength(50)][RegularExpression(@"^(Admin\|User\|Manager)$")] public string Role { get; set; } = "User"; |
model_user |
Complete User Domain Model | Full model with UserId, UserName, EmailAddress, PasswordHash, Role, IsActive |
model_login_vm, login_vm |
Login ViewModel | UserNameOrEmail, Password, RememberMe, ReturnUrl |
model_register_vm, signup_vm |
SignUp ViewModel | UserName, EmailAddress, Password, ConfirmPassword, Role |
model_report_vm |
Report Summary ViewModel | Category, TotalCount, TotalAmount, AverageAmount, ReportDate |
model_top_performers |
Top Performers ViewModel | Rank, EntityId, Name, TotalTransactions, TotalVolume |
2. Repository & BAL (Data Access & Reports)
| Trigger Prefix | Description | Generated Code Highlights |
|---|---|---|
getbycondition, bycondition |
Dynamic condition filter | Parameterized dynamic SQL condition with parameter reflection and try/finally |
search, repo_search |
Keyword full-text search | ILIKE / LIKE search across columns with try/finally |
getall, repo_getall |
GetAll records query | Queries table ordered by ID with inline reader mapping |
getbyid, repo_getbyid |
Single record by Primary Key | Selects record by ID with null safety and inline reader |
add, repo_add |
Insert record | Parameterized INSERT INTO returning boolean success |
update, repo_update |
Update record | Parameterized UPDATE SET returning boolean success |
delete, repo_delete |
Delete record | Parameterized DELETE FROM returning boolean success |
paged, repo_paged |
Pagination with TotalCount | Executes Count + LIMIT @pageSize OFFSET @offset returning (Items, TotalCount) |
auth_login, repo_login |
Authenticate user | Retrieves user credentials and verifies hash via BCrypt.Net.BCrypt.Verify |
email_exists |
Duplicate email check | SELECT COUNT(1) FROM ... WHERE emailaddress = @email |
report_summary, report |
Common aggregation report | SELECT Category, COUNT(*), SUM(Amount) with date range filters |
report_monthly |
Monthly breakdown report | Month-wise revenue/count aggregation using EXTRACT(MONTH FROM ...) |
report_top_performers |
Leaderboard report | Top N performers ranked by transaction count and revenue volume |
report_occupancy |
Capacity utilization report | Total seats vs. booked seats with calculated occupancy rate % |
export_csv, export |
In-memory CSV byte exporter | Formats query results into UTF-8 CSV byte stream |
3. Controller Actions (Role Authorization, Auth, Session & Kendo)
| Trigger Prefix | Description | Generated Code Highlights |
|---|---|---|
ctrl_role_view |
Role auth for Views | [Authorize(Roles = "Admin")] redirecting to AccessDenied view |
ctrl_role_json |
Role auth for JSON | Role-based check returning HTTP 403 Forbidden with custom error JSON |
ctrl_login, login_action |
Complete Login Flow (GET & POST) | Form validation, password verification, Session storage & Cookie claims sign-in |
ctrl_login_json |
Ajax JSON Login endpoint | JSON authentication endpoint returning user info and redirect URL |
ctrl_signup, signup_action |
Complete Register Flow (GET & POST) | Duplicate check, BCrypt password hashing, persistence, and redirect |
ctrl_logout, logout_action |
Logout action | Clears Session (HttpContext.Session.Clear()) and signs out Cookie auth |
ctrl_session_store, session_store |
Session state storage | Sets UserId, UserName, and UserRole in HttpContext.Session |
ctrl_session_clear, session_clear |
Session state clear | Clears HttpContext.Session and redirects to login |
kendo_read |
Kendo UI Grid Read action | [HttpPost] Read([DataSourceRequest] request) returning ToDataSourceResultAsync |
kendo_crud, ctrl_kendo_crud |
Complete Kendo Grid CRUD | Full endpoints for Read, Create, Update, and Destroy with ModelState |
ajax_save, ctrl_ajax_save |
Generic Ajax Save endpoint | [HttpPost] Save([FromBody] model) handling add or update based on model ID |
ctrl_export_csv, export_action |
Report File Download endpoint | Downloads CSV file via File(bytes, "text/csv", filename) |
⚙️ Extension Settings
Customize extension defaults in your VS Code settings.json:
{
// Default base namespace (if empty, auto-detected from nearest .csproj file)
"dotnetRepoGenerator.defaultNamespace": "",
// Default data access engine: "ADO.NET (SqlConnection)", "Dapper", or "Entity Framework Core"
"dotnetRepoGenerator.defaultDatabaseApproach": "ADO.NET (SqlConnection)",
// Default connection injected via DI: "NpgsqlConnection", "SqlConnection", or "IDbConnection"
"dotnetRepoGenerator.defaultConnectionType": "NpgsqlConnection",
// Default method execution style: "Async", "Sync", or "Both (Async + Sync)"
"dotnetRepoGenerator.defaultCodeStyle": "Async",
// Default primary key data type: "int", "long", or "Guid"
"dotnetRepoGenerator.defaultPrimaryKeyType": "int",
// Automatically open newly generated C# files in editor tabs
"dotnetRepoGenerator.autoOpenFiles": true
}
🧪 Development & Contribution
- Clone this repository:
git clone https://github.com/dotnet-community/dotnet-repo-generator.git cd dotnet-repo-generator npm install - Build the TypeScript source:
npm run compile - Press
F5to open the Extension Development Host to test and debug live in VS Code.
📜 License
Distributed under the MIT License. See LICENSE for details.