Introduction


This article will teach you how to use Microsoft's Blazor Stack Overflow's Dapper Micro-ORM to rapidly develop modern data-driven asynchronous websites. Many people prefer Dapper to Entity Framework because it's simple, lightweight, and doesn't hide the SQL code from you.

Step 1
Let's create the new project as below,

Name the project


Select .Net Core 3.1 and click on create


Step 2
Now let's install the Nuget packages


Step 3
Now let's create a database and tables
  1. CREATE TABLE [dbo].[Video] (
  2. [VideoID] INT IDENTITY (1, 1) NOT NULL,
  3. [Title] VARCHAR (128) NULL,
  4. [DatePublished] DATE NULL,
  5. [IsActive] BIT CONSTRAINT [DF_Video_IsActive] DEFAULT ((1)) NULL,
  6. CONSTRAINT [PK_Video] PRIMARY KEY CLUSTERED ([VideoID] ASC)
  7. );
Step 4
Now let's create classes to manage Data
  1. using System;
  2. // This is essentially a model for one row in the Video table.
  3. namespace BlazorDapperCRUD.Data
  4. {
  5. public class Video
  6. {
  7. public int VideoID { get; set; }
  8. public string Title { get; set; }
  9. public DateTime DatePublished { get; set; }
  10. public bool IsActive { get; set; }
  11. }
  12. }
  1. namespace BlazorDapperCRUD.Data
  2. {
  3. // Connection to SQL Server database, used within Data subfolder.
  4. public class SqlConnectionConfiguration
  5. {
  6. public SqlConnectionConfiguration(string value) => Value = value;
  7. public string Value { get; }
  8. }
  9. }
Step 5
Now let's create a service class and interface for crud operations
  1. using Dapper;
  2. using Microsoft.Data.SqlClient;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace BlazorDapperCRUD.Data
  9. {
  10. public class VideoService : IVideoService
  11. {
  12. // Database connection
  13. private readonly SqlConnectionConfiguration _configuration;
  14. public VideoService(SqlConnectionConfiguration configuration)
  15. {
  16. _configuration = configuration;
  17. }
  18. // Add (create) a Video table row (SQL Insert)
  19. public async Task<bool> VideoInsert(Video video)
  20. {
  21. using (var conn = new SqlConnection(_configuration.Value))
  22. {
  23. var parameters = new DynamicParameters();
  24. parameters.Add("Title", video.Title, DbType.String);
  25. parameters.Add("DatePublished", video.DatePublished, DbType.Date);
  26. parameters.Add("IsActive", video.IsActive, DbType.Boolean);
  27. // Stored procedure method
  28. await conn.ExecuteAsync("spVideo_Insert", parameters, commandType: CommandType.StoredProcedure);
  29. }
  30. return true;
  31. }
  32. // Get a list of video rows (SQL Select)
  33. public async Task<IEnumerable<Video>> VideoList()
  34. {
  35. IEnumerable<Video> videos;
  36. using (var conn = new SqlConnection(_configuration.Value))
  37. {
  38. videos = await conn.QueryAsync<Video>("spVideo_GetAll", commandType: CommandType.StoredProcedure);
  39. }
  40. return videos;
  41. }
  42. // Get one video based on its VideoID (SQL Select)
  43. public async Task<Video> Video_GetOne(int id)
  44. {
  45. Video video = new Video();
  46. var parameters = new DynamicParameters();
  47. parameters.Add("Id", id, DbType.Int32);
  48. using (var conn = new SqlConnection(_configuration.Value))
  49. {
  50. video = await conn.QueryFirstOrDefaultAsync<Video>("spVideo_GetOne", parameters, commandType: CommandType.StoredProcedure);
  51. }
  52. return video;
  53. }
  54. // Update one Video row based on its VideoID (SQL Update)
  55. public async Task<bool> VideoUpdate(Video video)
  56. {
  57. using (var conn = new SqlConnection(_configuration.Value))
  58. {
  59. var parameters = new DynamicParameters();
  60. parameters.Add("VideoID", video.VideoID, DbType.Int32);
  61. parameters.Add("Title", video.Title, DbType.String);
  62. parameters.Add("DatePublished", video.DatePublished, DbType.Date);
  63. parameters.Add("IsActive", video.IsActive, DbType.Boolean);
  64. await conn.ExecuteAsync("spVideo_Update", parameters, commandType: CommandType.StoredProcedure);
  65. }
  66. return true;
  67. }
  68. // Physically delete one Video row based on its VideoID (SQL Delete)
  69. public async Task<bool> VideoDelete(int id)
  70. {
  71. var parameters = new DynamicParameters();
  72. parameters.Add("Id", id, DbType.Int32);
  73. using (var conn = new SqlConnection(_configuration.Value))
  74. {
  75. await conn.ExecuteAsync("spVideo_Delete", parameters, commandType: CommandType.StoredProcedure);
  76. }
  77. return true;
  78. }
  79. }
  80. }
Step 6
Now let's add web pages to perform CRUD operations

  1. @using BlazorDapperCRUD.Data
  2. @page "/videoaddedit/{id:int}"
  3. @inject IVideoService VideoService
  4. @inject NavigationManager NavigationManager
  5. @*Okay to use DataAnnotationsValidator and ValidationSummary here, if you like. See...
  6. https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1*@
  7. <h1>@pagetitle</h1>
  8. <EditForm Model="@video" OnValidSubmit="@VideoSave">
  9. <table class="editform">
  10. <tr>
  11. <td>Video Title:</td>
  12. <td><input type="text" @bind="video.Title" required /></td>
  13. </tr>
  14. <tr>
  15. <td>Date Published:</td>
  16. <td><input type="date" @bind="video.DatePublished" required min="1900-01-01" max="2050-12-31" /></td>
  17. </tr>
  18. <tr>
  19. <td>Is Active:</td>
  20. <td><input type="checkbox" @bind="video.IsActive" /></td>
  21. </tr>
  22. <tr>
  23. <td colspan="2" style="text-align:center">
  24. <input type="submit" value="@buttontext" />
  25. <input type="button" value="Cancel" @onclick="@Cancel" />
  26. </td>
  27. </tr>
  28. </table>
  29. </EditForm>
  30. @code {
  31. // Create a new, empty Video object
  32. Video video = new Video();
  33. [Parameter]
  34. public int id { get; set; }
  35. // Set default page title and button text
  36. public string pagetitle = "Add a Video";
  37. public string buttontext = "Add";
  38. //Executes on page open, set defaults on page.
  39. protected override async Task OnInitializedAsync()
  40. {
  41. // ============ If the passed-in id is zero, assume new Video.
  42. if (id == 0)
  43. {
  44. DateTime defaultdate = new DateTime(2000, 12, 31);
  45. video.DatePublished = defaultdate;
  46. video.IsActive = true;
  47. }
  48. else
  49. {
  50. video = await VideoService.Video_GetOne(id);
  51. // Change page title and button text since this is an edit.
  52. pagetitle = "Edit Video";
  53. buttontext = "Update";
  54. }
  55. }
  56. protected async Task VideoSave()
  57. {
  58. if (video.VideoID == 0)
  59. {
  60. // Insert if id is zero.
  61. await VideoService.VideoInsert(video);
  62. }
  63. else
  64. {
  65. // Update if id not 0
  66. await VideoService.VideoUpdate(video);
  67. }
  68. NavigationManager.NavigateTo("/videolist");
  69. }
  70. void Cancel()
  71. {
  72. NavigationManager.NavigateTo("/videolist");
  73. }
  74. }

Conclusion


In this article, we discussed how to work with Blazor and Dapper using .Net core. I hope you all enjoyed reading this and learned from it. For better understanding download the source code.