How to do CRUD operations with NPoco in Umbraco 8

Posted written by Paul Seal on June 15, 2021 Umbraco

I will flesh this article out later, but here is some code as an example

using System;
using MyProject.Core.Models.Database;
using MyProject.Core.Repositories;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Scoping;

namespace MyProject.Core.Repositories
{
    public class LicenceRepository : ILicenceRepository
    {
        private static IScopeProvider _scopeProvider;

        public LicenceRepository(IScopeProvider scopeProvider)
        {
            _scopeProvider = scopeProvider;
        }

        public IEnumerable<LicenceDetails> GetAll()
        {
            using (var scope = _scopeProvider.CreateScope())
            {
                var db = scope.Database;
                var records = db.Query<LicenceDetails>("SELECT * FROM LicenceDetails");

                return records;
            }
        }

        public LicenceDetails Get(string licenceKey)
        {
            using (var scope = _scopeProvider.CreateScope())
            {
                var db = scope.Database;
                var record = db.Query<LicenceDetails>("SELECT * FROM LicenceDetails WHERE [LicenceKey] = @LicenceKey", new { licenceKey }).FirstOrDefault();

                return record;
            }
        }

        public void Create(LicenceDetails record)
        {
            using (var scope = _scopeProvider.CreateScope())
            {
                scope.Database.Insert(record);
                scope.Complete();
            }
        }

        public LicenceDetails Update(LicenceDetails record)
        {
            using (var scope = _scopeProvider.CreateScope())
            {
                scope.Database.Update(record);
                scope.Complete();
            }

            var item = Get(record.LicenceKey);

            return item;
        }

        public int Delete(string LicenceKey)
        {
            using (var scope = _scopeProvider.CreateScope())
            {
                var result = scope.Database.Delete<LicenceDetails>("WHERE [LicenceKey] = @LicenceKey", new { LicenceKey });
                scope.Complete();

                return result;
            }
        }
    }
}

Register it like this:

using MyProject.Core.Repositories;
using Umbraco.Core;
using Umbraco.Core.Composing;

namespace MyProjct.Core.Composing
{
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class RegisterServicesComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
            composition.Register<ILicenceRepository, LicenceRepository>(Lifetime.Singleton);
        }
    }
}

Use it like this:

using MyProject.Core.Models;
using MyProject.Core.Repositories;
using Newtonsoft.Json;
using Recaptcha.Web;
using Recaptcha.Web.Mvc;
using System;
using System.Linq;
using System.Web.Configuration;
using System.Web.Mvc;
using MyProject.Core.Enums;
using MyProject.Core.Models.Database;
using Umbraco.Web.Mvc;

namespace MyProject.Web.Controllers.Surface
{
    public class GenerateLicenceSurfaceController : SurfaceController
    {
        private readonly ILicenceRepository _licenceRepository;

        public GenerateLicenceSurfaceController(ILicenceRepository licenceRepository)
        {
            _licenceRepository = licenceRepository;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitGenerateLicenceForm(GenerateLicenceViewModel model)
        {
            var recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (!ModelState.IsValid) return CurrentUmbracoPage();

            try
            {
                SaveLicenceDetailsInDatabase(model.GumroadCode, domains, licence.Key);
                return RedirectToCurrentUmbracoPage();
            }
            catch (Exception ex)
            {
                Logger.Error(typeof(GenerateLicenceSurfaceController), ex, "Error when trying to create database record of licence details");
                return RedirectToCurrentUmbracoPage();
            }
        }

        private void SaveLicenceDetailsInDatabase(string suffix, string domains, string licenceKey)
        {
            var licenceRecord = new LicenceDetails()
            {
                LicenceKey = licenceKey,
                SuffixType = (int)SuffixType.GumroadCode,
                Suffix = suffix,
                ActivatedDate = DateTime.UtcNow,
                Domains = domains,
                IsSuspended = false
            };

            _licenceRepository.Create(licenceRecord);
        }
    }
}