ondercode
TR EN

10 November 2026 · 9 min read

Architecture for WinForms ERP: Classic Layers (Entity–DAL–BL–UI) or EF Core?

Which architecture works best for a WinForms ERP? I compare the classic Entity–DAL–BL–UI layers with the EF Core approach using one scenario, code samples, pros, cons and a comparison table, and end with the hybrid model that works in practice.

  • Mimari
  • WinForms
  • ERP
  • EF Core
  • ADO.NET
  • C#

Before you design a single screen of an ERP system, there is a decision to make: where does the data come from, how does it flow, and which layer is responsible for it? I have been building ERP screens with WinForms for years, and most projects I have seen took one of two paths: the classic Entity–DAL–BL–UI layered architecture, or a modern approach centered on EF Core. In this post I walk through both with the same scenario, lay out their pros and cons honestly, and finish with the model I have found healthiest in practice.

I covered the screen side (look and feel, theming and the MVP pattern) in WinForms Is Not Dead. This post is about the layers behind the screen.

The scenario: saving an invoice

Let's keep one example throughout. A user picks a customer on the invoice screen, enters the lines and clicks Save. Behind the scenes:

  1. The customer's credit limit must be checked.
  2. The invoice header and lines must be written.
  3. Stock must be decreased and the customer balance updated.
  4. If any step fails, nothing must be written (a single transaction).

These four requirements are the best test of an architecture's quality.

1. Classic layered architecture: Entity–DAL–BL–UI

A large share of ERP systems are built this way. The solution is usually split into four projects:

Layer Project Responsibility
Entity (OBJ / Model) Erp.Entity Plain classes that mirror tables: Invoice, InvoiceLine, Customer
DAL (Data Access Layer) Erp.DAL The only place that talks to the database: SQL, parameters, stored procedure calls, mapping rows to objects
BL (Business Layer) Erp.BL Business rules: credit checks, stock updates, transaction handling
UI Erp.UI Forms. They only call the BL and know nothing about SQL

Dependencies go one way: UI → BL → DAL → Database, and the entities are the shared language of every layer.

The DAL is usually written with ADO.NET:

public sealed class InvoiceDal
{
    public void Insert(Invoice inv, SqlConnection cn, SqlTransaction tx)
    {
        using var cmd = new SqlCommand(
            "INSERT INTO Invoice (No, CustomerId, Date, Total) " +
            "VALUES (@No, @CustomerId, @Date, @Total); SELECT SCOPE_IDENTITY();", cn, tx);
        cmd.Parameters.AddWithValue("@No", inv.No);
        cmd.Parameters.AddWithValue("@CustomerId", inv.CustomerId);
        cmd.Parameters.AddWithValue("@Date", inv.Date);
        cmd.Parameters.AddWithValue("@Total", inv.Total);
        inv.Id = Convert.ToInt32(cmd.ExecuteScalar());
    }
}

Business rules and the transaction live in the BL:

public sealed class InvoiceBl
{
    public void Save(Invoice inv)
    {
        using var cn = Db.Open();
        using var tx = cn.BeginTransaction();
        try
        {
            var customer = _customerDal.Get(inv.CustomerId, cn, tx);
            if (customer.Balance + inv.Total > customer.CreditLimit)
                throw new BusinessException("The customer's credit limit would be exceeded.");

            _invoiceDal.Insert(inv, cn, tx);
            foreach (var line in inv.Lines)
            {
                line.InvoiceId = inv.Id;
                _lineDal.Insert(line, cn, tx);
                _stockDal.Decrease(line.ProductId, line.Quantity, cn, tx);
            }
            _customerDal.AddBalance(inv.CustomerId, inv.Total, cn, tx);
            tx.Commit();
        }
        catch
        {
            tx.Rollback();
            throw;
        }
    }
}

And the form only knows this much:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        _invoiceBl.Save(ReadInvoiceFromScreen());
        ShowSuccess("Invoice saved.");
    }
    catch (BusinessException ex)
    {
        ShowWarning(ex.Message);
    }
}

Pros

  • Full control and performance. You write the SQL that runs, so indexes, query plans and locking behave predictably. Excellent for heavy reports and batch jobs.
  • DBA- and stored-procedure-friendly. If part of the logic lives in PL/SQL or T-SQL, this structure works with it naturally.
  • Predictability. Anyone reading the code can see exactly what hits the database, which makes debugging easy.
  • Widely known. A new developer who knows ADO.NET and SQL can contribute on day one.
  • Clear boundaries. Done right, not a single line of SQL remains in the forms.

Cons

  • Repetitive code. Every table needs Insert, Update, Delete, Get and mapping code. In an ERP with hundreds of tables, that is thousands of lines.
  • Schema changes hurt. Adding a column means updating the entity, the DAL's SQL and the mapping code separately; whatever you forget fails at runtime.
  • SQL lives as strings. A typo or a wrong column name shows up on the user's screen, not at compile time.
  • The "thin BL" trap. Over time the BL turns into an empty pass-through to the DAL, and the real rules leak into stored procedures or forms.
  • Passing transactions around. Threading the connection and transaction through every method is noisy and error-prone.
  • Hard to test. Static DAL classes and direct SqlConnection usage make it almost impossible to test business rules without a database.

2. The EF Core approach

With EF Core most of the DAL disappears. The entities stay the same, and the layer that talks to the database becomes a DbContext:

public sealed class ErpContext(DbContextOptions<ErpContext> options) : DbContext(options)
{
    public DbSet<Invoice> Invoices => Set<Invoice>();
    public DbSet<Customer> Customers => Set<Customer>();
    public DbSet<Product> Products => Set<Product>();
}

The same invoice save in a service class:

public sealed class InvoiceService(IDbContextFactory<ErpContext> factory)
{
    public async Task SaveAsync(Invoice inv)
    {
        await using var db = await factory.CreateDbContextAsync();
        await using var tx = await db.Database.BeginTransactionAsync();

        var customer = await db.Customers.FindAsync(inv.CustomerId)
            ?? throw new BusinessException("Customer not found.");
        if (customer.Balance + inv.Total > customer.CreditLimit)
            throw new BusinessException("The customer's credit limit would be exceeded.");

        db.Invoices.Add(inv);           // header and lines are added together
        customer.Balance += inv.Total;  // change tracking generates the UPDATE
        await db.SaveChangesAsync();

        // Stock: a direct UPDATE without loading products into memory
        foreach (var line in inv.Lines)
            await db.Products.Where(p => p.Id == line.ProductId)
                .ExecuteUpdateAsync(s => s.SetProperty(p => p.Stock, p => p.Stock - line.Quantity));

        await tx.CommitAsync();
    }
}

Note the subtlety: ExecuteUpdate runs immediately, without waiting for SaveChanges. To keep everything in one unit, we start the transaction explicitly. Using EF Core well means knowing details like this.

On the WinForms side the most important topic is DbContext lifetime. A single context that lives as long as the form is open is the most common mistake: change tracking grows, memory climbs and you never see changes made by other users. Use a short-lived context per operation instead, and load lists without tracking, selecting only the columns you need:

await using var db = await factory.CreateDbContextAsync();
grid.DataSource = await db.Customers.AsNoTracking()
    .Where(c => c.IsActive)
    .OrderBy(c => c.Name)
    .Select(c => new CustomerRow(c.Code, c.Name, c.City, c.Balance))
    .ToListAsync();

Microsoft.Extensions.DependencyInjection works perfectly well in WinForms for wiring services into forms:

var services = new ServiceCollection();
services.AddDbContextFactory<ErpContext>(o => o.UseSqlServer(connectionString));
services.AddTransient<InvoiceService>();
services.AddTransient<MainForm>();

using var provider = services.BuildServiceProvider();
Application.Run(provider.GetRequiredService<MainForm>());

Pros

  • Far less code. CRUD, parameters and mapping are automatic; simple definition screens are done in minutes.
  • Type safety. A wrong column name in a LINQ query is caught at compile time, and renames are safe.
  • Change tracking and unit of work. SaveChanges writes all pending changes in a single transaction.
  • Migrations. Schema changes are tied to code and versioned, so test and production databases stay in sync.
  • Testability. Services come through DI, and business rules can be tested quickly against SQLite.
  • Fits modern .NET. Works naturally with async/await, DI and logging, with providers for SQL Server, PostgreSQL, Oracle and SQLite.

Cons

  • You must watch the generated SQL. N+1 queries from lazy loading, cartesian explosion from many Includes (fixed with AsSplitQuery) and unnecessary columns (fixed with projection) are common. Check queries with ToQueryString() and logging.
  • Heavy reports and batch jobs. ExecuteUpdate and ExecuteDelete help a lot, but hand-written SQL is still faster and clearer for complex reports.
  • Legacy schemas. Composite keys, triggers and stored-procedure-heavy designs need extra configuration.
  • Lifetime mistakes. A long-lived context and synchronous queries on the UI thread freeze WinForms screens.
  • Learning curve. Tracking behavior, relationships and migration conflicts require experience in the team.
  • Hidden cost. The "everything is automatic" feeling can produce a team that never thinks about the database. EF Core does not replace SQL skills.

Side by side

Criterion Classic (ADO.NET) EF Core
Amount of code High Low
Control over SQL Full Medium (needs monitoring)
Speed of building simple CRUD Slow Very fast
Heavy reports and batch jobs Excellent Medium (good with raw SQL)
Schema changes Laborious, error-prone Controlled with migrations
Where errors are caught Runtime Mostly compile time
Testability Hard Easy
Stored procedures and legacy schemas Natural Needs adapting
Learning curve Low Medium

My recommendation: keep the layers, mix data access wisely

What worked best in practice was not turning either option into dogma, but keeping the layer discipline and giving each job the right tool:

  1. Keep the layers. UI → Service (BL) → Data. Forms contain neither SQL nor a DbContext; they only call services.
  2. Business rules live in services. Credit checks, stock updates and approval flows must not leak into stored procedures or Click handlers.
  3. EF Core for everyday CRUD and units of work. Definition screens, document entry and related data.
  4. Raw SQL for reports, batch jobs and critical queries. Use Dapper or FromSql, keep these queries in a separate "Queries" folder and measure them.
  5. Don't blindly wrap EF Core in a generic repository. DbContext already is a unit of work and DbSet already is a repository. If you need an abstraction, make it business-oriented, like IInvoiceService.SaveAsync.
  6. Keep contexts short-lived. One context per operation via IDbContextFactory; lists with AsNoTracking.
  7. Make everything async. Awaited queries don't freeze the screen; show a busy state on the button while waiting.
  8. Use DI. Forms receive their services through the constructor, and dependencies are managed in one place.

If you have a large, working ADO.NET codebase, don't change everything at once. Write new modules with this model and bring the layer discipline to old modules whenever you touch them. Within a few releases the center of gravity of the codebase shifts on its own.

Conclusion

The classic Entity–DAL–BL–UI structure gives you control and predictability, and charges you in repetitive code and costly maintenance. EF Core gives you speed, type safety and testability, and charges you the obligation to manage generated SQL and context lifetime consciously. A good ERP architecture is less about choosing one of them and more about keeping layer discipline and giving each job the right tool.

To modernize the screens themselves, you can also download the demo of Onda, the WinForms component framework I build.

Comments

No comments yet. Be the first to share what you think.

Leave a comment

Comments appear after I review them.