📜  Dapper Get - C# (1)

📅  最后修改于: 2023-12-03 15:14:35.862000             🧑  作者: Mango

Dapper Get - C#

Dapper is a simple and fast object mapper for .NET, which is used to map database objects to C# objects. It provides a minimalistic interface for querying and storing data in a database, and it is very popular among .NET developers.

Getting Started with Dapper Get

To start using Dapper, you must first install the Dapper NuGet package. You can do this by using the following command in the Package Manager Console:

Install-Package Dapper
Connecting to the Database

Before you can start querying the database, you need to establish a connection. Dapper provides you with various ways to connect to a database, but the most common way is to use the SqlConnection class:

using(var connection = new SqlConnection(connectionString))
{
    // your code here
}

Here connectionString is the connection string to your database. You should replace it with your own.

Querying the Database

With Dapper, you can retrieve data from the database using the Query method. This method returns an IEnumerable of the specified type. You can pass in the SQL query as a string, and optionally pass in any parameters:

var products = connection.Query<Product>("SELECT * FROM Products");

Here, Product is a C# class that represents the database table. Dapper maps the columns in the database table to the properties of the Product class.

You can also use Dapper to retrieve a single record from the database using the QuerySingleOrDefault method:

var product = connection.QuerySingleOrDefault<Product>("SELECT * FROM Products WHERE Id = @Id", new { Id = 1 });

Here, Id is a parameter that is passed into the query.

You can also use Dapper to execute a SQL command that doesn't return a result set, such as an INSERT, UPDATE, or DELETE statement:

connection.Execute("INSERT INTO Products (Name, Price) VALUES (@Name, @Price)", new { Name = "Widget", Price = 19.99 });

Here, Name and Price are parameters that are passed into the query.

Conclusion

Dapper is a lightweight and fast ORM that is very easy to use. It supports multiple database providers and provides a seamless experience for querying and storing data. Give it a try!