This guide outlines how to use Dapper.Rainbow
in C# for CRUD operations.
Add Dapper and Dapper.Rainbow to your project via NuGet:
Install-Package Dapper -Version x.x.x
Install-Package Dapper.Rainbow -Version x.x.x
Replace x.x.x
with the latest version numbers.
For Dapper.Rainbow
to function correctly, ensure each table has a primary key column named Id
.
Example Users
table schema:
CREATE TABLE Users (
Id INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100)
);
Open a connection to your database:
using System.Data.SqlClient;
var connectionString = "your_connection_string_here";
using var connection = new SqlConnection(connectionString);
connection.Open(); // Open the connection
Define a class for your database context:
using Dapper;
using System.Data;
public class MyDatabase : Database<MyDatabase>
{
public Table<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
var db = new MyDatabase { Connection = connection };
var newUser = new User { Name = "John Doe", Email = "[email protected]" };
var insertedUser = db.Users.Insert(newUser);
Fetch users by ID or all users:
var user = db.Users.Get(id); // Single user by ID
var users = connection.Query<User>("SELECT * FROM Users"); // All users
var userToUpdate = db.Users.Get(id);
userToUpdate.Email = "[email protected]";
db.Users.Update(userToUpdate);
db.Users.Delete(id);
Example schema for a Posts
table with a foreign key to Users
:
CREATE TABLE Posts (
Id INT IDENTITY(1,1) PRIMARY KEY,
UserId INT,
Content VARCHAR(255),
FOREIGN KEY (UserId) REFERENCES Users(Id)
);
Inserting a parent (User
) and a child (Post
) row:
var newUser = new User { Name = "Jane Doe", Email = "[email protected]" };
var userId = db.Users.Insert(newUser);
var newPost = new Post { UserId = userId, Content = "Hello, World!" };
db.Connection.Insert(newPost); // Using Dapper for the child table