Dapper - Getting Started with Dapper

CSharp · Console

/Program.cs

// Learn Dapper
// Doc: https://www.learndapper.com/

// @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 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() { ProductName = "Dapper Plus", SupplierID = 1, CategoryID = 1, UnitPrice = 999, UnitsInStock = 1000, UnitsOnOrder = 20, Discontinued = false});
			seedProducts.Add(new Product() { ProductName = "C# Eval Expression", SupplierID = 1, CategoryID = 2, UnitPrice = 499, UnitsInStock = 500, UnitsOnOrder = 10, Discontinued = false });
			seedProducts.Add(new Product() { ProductName = "Entity Framework Extensions", SupplierID = 2, CategoryID = 1, UnitPrice = 999, UnitsInStock = 3000, UnitsOnOrder = 60, Discontinued = false });

			// BulkInsert data (from Dapper Plus)
			connection.BulkInsert(seedProducts);
		}
		
		// Query data with Dapper
		FiddleHelper.WriteTable(connection.Query<Product>("SELECT * FROM Product"));
	}
	
	[Table("Product")]
	public class Product
	{
		[Key]
		[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
		public int ProductID { get; set; }
		public string ProductName { get; set; }
		public int SupplierID { get; set; }
		public int CategoryID { get; set; }
		public decimal UnitPrice { get; set; }
		public int UnitsInStock { get; set; }
		public int UnitsOnOrder { get; set; }
		public bool Discontinued { get; set; }
		public DateTime? DiscontinuedDate { get; set; }
	}
}
;