Skip to content

SimpleCRUD is a .NET library that simplifies creation of basic CRUD operations on databases by providing a generic template has a repository pattern design template.

License

Notifications You must be signed in to change notification settings

Paciente8159/SimpleCRUD

Repository files navigation

SimpleCRUD

SimpleCRUD is a .NET library that simplifies creation of basic CRUD operations on databases by providing a generic template has a repository pattern design template. Can be used in Web API and MVC injections services.

Getting Started

To use this library simply download it and add it to your .NET project file (.csproj).

<ItemGroup>
    <ProjectReference Include="${Path to the SimpleCRUD project}\SimpleCRUD.csproj" />
</ItemGroup>

Step 1

The hard part. This is a template. No driver or database engine is included so you have to implement a generic repository that will implement your CRUD (Create/Read/Update/Delete) operations. This class must inherit the ICRUDRepository. To support The following exemple uses a List to simulate as database table.

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.Reflection;
using System.Linq;
using System.Threading.Tasks;
using SimpleCRUD;

namespace Example
{
    public abstract class GenericRepository<T> : ICRUDRepository <T>
        where T : class, new()
    {
        //you object that will act has your database in this exemple it's a simple list
        internal List<T> _values;

        //gets the PropertyInfo that will allow you to get the model primary key value
        private readonly PropertyInfo _pk = CRUDModelPKAttribute.GetPKProperty<T>();
        //gets a boolean indicating if the primary key is auto generated value
        //adicional logic may be needed if this value is true
        private readonly bool _autogenerated = CRUDModelPKAttribute.IsAutoGenerated<T>();

        //Initializes the generic repository
        //the constructor takes an IConfiguration object
        //The IConfiguration is injected by using by MVC services
        public GenericRepository(IConfiguration config)
        {
            /* 
                Initialize you data 
                Connect to your database and retrieve you database collection
            */
            _values = new List<T>();

            //Checks if the model has a primary key
            if(_pk == null)
            {
                throw new CustomAttributeFormatException(string.Format("Class {0} doesn't define a primary key property (CRUDModelPK attribute)", typeof(T).Name));
            }
        }

        public async Task<List<T>> ReadAll()
        {
            return _values;
        }

        public async Task<T> Read(object key)
        {
            return _values.FirstOrDefault(val => key.Equals(_pk.GetValue(val)));
        }

        public async Task<T> Create(T value)
        {
            _values.Add(value);
            return value;
        }

        public async Task<bool> Update(object key, T value)
        {
            T item = _values.FirstOrDefault(val => key.Equals(_pk.GetValue(val)));
            if(item == null)
            {
                return false;
            }
            
            _values[_values.IndexOf(item)] = value;
            return true;
        }

        public async Task<bool> Delete(object key)
        {
            T item = _values.FirstOrDefault(val => key.Equals(_pk.GetValue(val)));
            if(item != null)
            {
                _values.Remove(item);
            }

            return true;
        }

    }
}

Step 2

To use it simply add the CRUDModelPK attribute to each model primary key

using System;
using SimpleCRUD;

namespace Example
{
    public class MyModel
    {
        [CRUDModelPK]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public int Phone { get; set; }
    }
}

Step 3

Create the corresponding ICRUDInterface to be injected on your MVC services for each model.

using System;
using SimpleCRUD;

namespace Example
{
    public interface IMyModelRepository : ICRUDRepository<MyModel>
    {
    }
}

Step 4

After this you are lunched. For each model create it's custom repository inheriting this base class.

using System;
using Microsoft.Extensions.Configuration;
using SimpleCRUD;

namespace Example
{
    public class MyModelRepository : GenericRepository<MyModelRepository, IMyModelRepository>
    {
        public MyModelRepository(IConfiguration config) : base(config)
        {
        }
    }
}

And in the controllers folder add the corresponding custom CRUDController.

Step 5

using System;
using Microsoft.AspNetCore.Mvc;
using SimpleCRUD;

namespace Example
{
    [Route("api/[controller]")]
    [ApiController]
    public class MyModelController : CRUDControllerBase<MyModel, IMyModelRepository>
    {
        public MyModelController(IMyModelRepository repository) : base(repository)
        {
        }
    }
}

That's it. For all Models in your app repeat steps 2 to 5. If you desire to do more complex CRUD operations you can do them directly in your derived Repository and Controller classes.

Prerequisites

None.

Installing/Compiling the code

Install .Net Core version 2.2 or above.

To compile the code library just open a terminal in the project folder and type

dotnet build

Or build using Release configuration sh

dotnet build --configuration Release

Built With

Authors

  • João Martins (Paciente8159) - Initial work - Paciente8159

License

This project is licensed under the MIT License - see the LICENSE file for details

About

SimpleCRUD is a .NET library that simplifies creation of basic CRUD operations on databases by providing a generic template has a repository pattern design template.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages