Creating a MooDbContext
What this page covers#
This page explains the two ways to create a MooDbContext.
Why there are two options#
Sometimes the simplest thing is to hand MooDbContext a connection string and let it create a connection as needed.
Other times your application already has a SqlConnection and wants MooDb to use that connection.
MooDb supports both.
Option 1: use a connection string#
using MooDb; var db = new MooDbContext(connectionString);
What this means#
When you create MooDbContext with a connection string:
- MooDb creates connections for operations when it needs them
- MooDb manages those operation-level connections for you
- this is usually the easiest way to start
Option 2: use an existing SqlConnection#
using Microsoft.Data.SqlClient; using MooDb; await using var connection = new SqlConnection(connectionString); var db = new MooDbContext(connection);
What this means#
When you create MooDbContext with an existing SqlConnection:
- you supply the connection object
- your code owns the broader connection lifetime
- MooDb uses that connection for its commands
Optional configuration with MooDbContextOptions#
var db = new MooDbContext(connectionString, new MooDbContextOptions { CommandTimeoutSeconds = 60, StrictAutoMapping = true });
When to use each approach#
Use a connection string when:
- you want the simplest entry point
- you do not need to share a connection object yourself
- you want MooDb to create the per-operation connection for you
Use an existing SqlConnection when:
- your calling code already owns the connection
- you are integrating with existing infrastructure
- you want explicit connection control