CSharp · Console
// Learn Dapper
// Doc: https://www.learndapper.com/execute-reader
// @nuget: Dapper
// @nuget: Microsoft.Data.SqlClient
// @nuget: Z.Dapper.Plus
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.Data.SqlClient;
using Dapper;
using Z.Dapper.Plus;
public class Program
{
public static void Main()
{
var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer());
// CREATE database and data seeding
{
// CREATE Table (from Dapper Plus)
connection.CreateTable<Product>();
var seedProducts = new List<Product>();
seedProducts.Add(new Product() { Name = "Dapper Plus", CategoryID = 1, Description = @"Use <a href=""https://dapper-plus.net/"" target=""_blank"">Dapper Plus</a> to extend your IDbConnection with high-performance bulk operations." });
seedProducts.Add(new Product() { Name = "C# Eval Expression", CategoryID = 2, Description = @"Use <a href=""https://eval-expression.net/"" target=""_blank"">C# Eval Expression</a> to compile and execute C# code at runtime." });
seedProducts.Add(new Product() { Name = "Entity Framework Extensions", CategoryID = 1, Description = @"Use <a href=""https://entityframework-extensions.net/"" target=""_blank"">Entity Framework Extensions</a> to extend your DbContext with high-performance bulk operations." });
// BulkInsert data (from Dapper Plus)
connection.BulkInsert(seedProducts);
}
// Insert data with Dapper
var sql1 = "DELETE FROM Product WHERE CategoryID = @categoryID";
connection.Execute(sql1, new { categoryID = 2 });
// Query data with Dapper
var sql2 = "SELECT * FROM Product";
var products = connection.Query<Product>(sql2).ToList();
FiddleHelper.WriteTable(products);
}
[Table("Product")]
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductID { get; set; }
public int CategoryID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}