Okay, so I wanted to mess around with Dapper, you know, that micro-ORM from the Stack Overflow folks. And I’ve heard about this “Jack Rogers” thing related to Dapper, so I figured I’d give it a shot. It’s supposed to make things even easier, I guess.
Getting Started
First things first, I needed a project. I just spun up a simple .NET console app. Nothing fancy, just the basic template.
Then I fire up Visual Studio and started add packages through NuGet.
Dapper-Of course,gotta install Dapper itself.
-Also use *.
-I’m using SQL Server for this, so I grabbed the SQL Server client.
Setting up the Database
Next, I needed a database. I already had SQL Server installed locally, so I just created a new database called “TestDB”. Then, I made a simple table:
CREATE TABLE MyTestTable (
Id INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR(50),
Age INT
Nothing special, just an Id, a Name, and an Age. Good enough for testing.
Coding Time
Now for the actual code. I created a class to represent my table:
public class MyTestObject
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
See? Matches the table perfectly.
Then, I wrote the code to connect to the database and do some basic operations. First connect database by connection string
string connectionString = "your connection string"; //I put my connection string here.
using (var connection = new SqlConnection(connectionString))
Inserting Data
Let’s insert some data.
var newObject = new MyTestObject { Name = "Bob", Age = 30 };
var id = *(newObject);
Used `*(newObject)`,so easy!
Getting Data
Now, how about getting data back? Here that things
var myObject = *<MyTestObject>(id);
If wanna to get all of * this:
var allObjects = *<MyTestObject>();
Updating and Deleting
Updating is just as simple,I think:
* = "Robert"; // Changed my mind
*(myObject);
And deleting:
*(myObject);
Wrapping Up
So, yeah, that’s pretty much it. Dapper, along with *, makes working with databases in .NET feel way less painful. I can see why people like it. It’s straightforward, and you don’t have to write a ton of boilerplate SQL. It’s all pretty intuitive. I just followed the basic examples, and it all worked! I might actually use this in a real project sometime.