Skip to content
| Marketplace
Sign in
Visual Studio Code>Programming Languages>C# .NET Repository Pattern & BAL GeneratorNew to Visual Studio Code? Get it now.
C# .NET Repository Pattern & BAL Generator

C# .NET Repository Pattern & BAL Generator

Thor

|
2 installs
| (0) | Free
Generate enterprise-grade Repository Pattern, BAL Helpers, Models with Data Annotations, and Controllers (MVC, Ajax, Kendo UI) for .NET and C# MVC projects.
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

C# .NET Repository Pattern & BAL Generator for VS Code

Visual Studio Marketplace Version License .NET Version TypeScript Strict Database Engines

An 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

  • 🚀 Zero Boilerplate: Scaffolds full end-to-end multi-tier architectures in under 5 seconds.
  • 🏷️ Smart Name Stripping: Enter table names like t_User or vm_Event — the model class retains t_User, while Interfaces, Repositories, Helpers, and Controllers automatically use clean, idiomatic names (IUserInterface, UserRepository, UserHelper, UserController).
  • 🔠 Strict PascalCase & Data Annotations: Converts column inputs (eventname, totalseats, email) into clean C# properties (EventName, TotalSeats, EmailAddress) decorated with validation attributes ([Required], [EmailAddress], [Phone], [Range], [Compare], [Key]).
  • 🔌 Constructor DI Connection Lifecycle: Uses connection injected via constructor (matching DI in Program.cs). Methods execute inside safe try { await _conn.OpenAsync(); ... } finally { await _conn.CloseAsync(); } blocks to eliminate connection leaks.
  • ⚡ Direct Inline Reader Mapping: Eliminates reflection mapper overhead. DataReader columns are mapped directly inside reader loops.
  • 🌐 3 Controller Flavors: Generates Razor View Controllers, Ajax/JSON RESTful Controllers, or Telerik Kendo UI Grid Controllers.
  • 🔒 Role-Based Authorization & Session Management: Built-in support for role authorization (Admin, Manager, User), Session storage/clear, and complete Login/SignUp/Logout workflows.
  • 📊 Enterprise Business Reports: Built-in methods and snippets for Summary Aggregation, Monthly Breakdowns, Top Performers, Seat Occupancy, Audit Logs, and CSV Export.
  • 💡 Instant Snippet Autocomplete: 30+ context-aware snippets for Models, Interfaces, Repositories, BAL Helpers, and Controllers.

🏗️ Architecture Styles: Repository vs. BAL

Choose the pattern that matches your project architecture:

Feature Repository Pattern BAL Pattern (Business Access Layer)
Structure Model + Interface + Implementation Model + Direct Helper Implementation
Decoupling High (Interface contracts for DI & Unit Testing) Direct (Rapid development & service reuse)
Naming I{CleanName}Interface & {CleanName}Repository {CleanName}Helper (e.g. UserHelper.cs)
Folder Layout Models/, Interfaces/, Implementation/ Models/, BAL/
Interface Required? Yes (IUserInterface.cs) No interface needed
Best For Large enterprise apps, Clean Architecture Business logic services, reporting helpers, MVC apps

Directory Architecture

Repository Pattern Layout

{SelectedFolder}/
├── Models/
│   └── t_User.cs                  # Entity model with PascalCase & Data Annotations
├── Interfaces/
│   └── IUserInterface.cs          # Contract with clean naming (IUserInterface)
├── Implementation/
│   └── UserRepository.cs          # ADO.NET / Dapper / EF Core repository
└── Controllers/                   # Optional
    └── UserController.cs          # MVC View, Ajax/JSON, or Kendo UI controller

BAL Pattern Layout

{SelectedFolder}/
├── Models/
│   └── t_User.cs                  # Entity model with PascalCase & Data Annotations
├── BAL/
│   └── UserHelper.cs              # Direct Helper class with queries & business methods
└── Controllers/                   # Optional
    └── UserController.cs          # Injects UserHelper directly

🚀 Quick Start & Usage

Method 1: Right-Click Context Menu (Recommended)

  1. In the VS Code File Explorer, right-click on any folder.
  2. Select .NET Repository & BAL Generator:
    • Generate Repository or BAL Pattern (Complete end-to-end wizard)
    • Generate Model Only
    • Generate Interface Only
    • Generate Repository Implementation Only
    • Generate BAL Helper Only
    • Generate Controller Only (View / Ajax / Kendo)

Method 2: Command Palette

  1. Press Ctrl + Shift + P (or Cmd + Shift + P on macOS).
  2. Type dotnet or Generate Repository and press Enter.

📋 Interactive Guided Wizard

When generating code, the extension guides you through an intuitive, multi-step flow:

┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. Architecture Pattern │ Pick "Repository Pattern" or "BAL Pattern"        │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 2. Entity / Model Name  │ e.g. "t_User", "vm_Event", or "EventModel"        │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 3. Controller Style     │ Pick "MVC View", "Ajax / JSON", "Kendo UI", "None"│
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 4. Primary Key Type     │ Select "int", "long", or "Guid"                   │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 5. Properties           │ QuickPick common fields (Email, Phone, Date, etc.)│
│                         │ + custom "name:type" inputs                       │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 6. Code Style           │ Pick "Async", "Sync", or "Both (Async + Sync)"    │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 7. Database Engine      │ Pick "ADO.NET", "Dapper", or "EF Core"            │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 8. Injected Connection  │ Pick "NpgsqlConnection", "SqlConnection", or      │
│                         │ "IDbConnection" (matches Program.cs registration) │
├─────────────────────────┼───────────────────────────────────────────────────┤
│ 9. Operations           │ Multi-select: GetAll, GetById, Add, Update,       │
│                         │ Delete, Search, GetByCondition, GetPaged, Count   │
└─────────────────────────────────────────────────────────────────────────────┘

🔒 Role-Based Authorization Integration

The extension supports role-based security tailored for both Razor Views and JSON APIs / Ajax:

1. Role-Based for MVC Razor Views

Used for server-rendered HTML pages where unauthorized users should be redirected:

[Authorize(Roles = "Admin,Manager")]
public IActionResult AdminDashboard()
{
    if (!User.IsInRole("Admin"))
    {
        return RedirectToAction("AccessDenied", "Account");
    }
    return View();
}

[HttpGet]
[AllowAnonymous]
public IActionResult AccessDenied()
{
    return View();
}

2. Role-Based for Ajax / JSON APIs

Used for SPA / client-side Ajax calls where unauthorized requests return standard JSON and HTTP 403 status:

[HttpPost]
[Authorize]
public async Task<IActionResult> AdminAction([FromBody] RequestModel model)
{
    if (!User.IsInRole("Admin"))
    {
        return StatusCode(StatusCodes.Status403Forbidden, new 
        { 
            success = false, 
            message = "Access Denied: Requires Admin role permissions." 
        });
    }

    // Process secure action
    return Json(new { success = true, message = "Executed successfully" });
}

🔑 Session & Authentication Setup (Program.cs)

To use the generated login, session, and DI connection features, add the following to your Program.cs:

// 1. Register Database Connection via DI
builder.Services.AddScoped<NpgsqlConnection>(sp => 
    new NpgsqlConnection(builder.Configuration.GetConnectionString("DefaultConnection")));

// 2. Register Repository or BAL Helper
builder.Services.AddScoped<IUserInterface, UserRepository>();
// or for BAL:
// builder.Services.AddScoped<UserHelper>();

// 3. Register Session
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

// 4. Register Cookie Authentication
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
        options.ExpireTimeSpan = TimeSpan.FromDays(7);
    });

// Middleware pipeline
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();

💡 Comprehensive Code Snippets Reference

Typing prefixes in .cs files triggers intelligent, production-ready code snippets:

1. Models & ViewModels

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

  1. Clone this repository:
    git clone https://github.com/dotnet-community/dotnet-repo-generator.git
    cd dotnet-repo-generator
    npm install
    
  2. Build the TypeScript source:
    npm run compile
    
  3. Press F5 to open the Extension Development Host to test and debug live in VS Code.

📜 License

Distributed under the MIT License. See LICENSE for details.

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
  • Your Privacy Choices
  • Consumer Health Privacy
© 2026 Microsoft