• Stars
    star
    598
  • Rank 74,853 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created over 6 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library to help you quickly code CRUD accesses for a web/mobile/desktop application using EF Core.

EfCore.GenericServices

This library helps you quickly code Create, Read, Update and Delete (CRUD) accesses for a web/mobile/desktop application. It acts as a adapter and command pattern between a database accessed by Entity Framework Core (EF Core) and the needs of the front-end system.

The EfCore.GenericServices library is available on NuGet as EfCore.GenericServices and is an open-source library under the MIT licence. See ReleaseNotes for details of changes and information on each version of EfCore.GenericServices.

NOTE: Version 5.1.0 and above of this library supports multiple versions of EF Core 5.

  • Version 5.1.0 and above supports EF Core 5.10 and EF Core 6.0
  • Version 5.2.0 and above supports EF Core 5.10, EF Core 6.0 and EF Core 7.0

If are using the older versions of EF Core you should use EfCore.GenericServices, version 3.2.2.

Documentation and useful articles

The documentation can be found in the GitHub wiki. but the rest of this README file provides a good overview of what the library can do, but here are some articles that give you a detailed description of what the libraray does.

What the library does

This library takes advantage of the fact that each of the four CRUD database accesses differ in what they do, but they have a common set of data part they all use, which are:

a) What database class/table do you want to access? b) What properties in that class/table do you want to access or change?

This library uses DTOs (data transfer objects, also known as ViewModels) plus a special interface to define the class/table and the properties to access. That allows the library to implement a generic solution for each of the four CRUD accesses, where the only thing that changes is the DTO you use.

Typical web applications have hundreds of CRUD pages - display this, edit that, delete the other - and each CRUD access has to adapt the data in the database to show the user, and then apply the changes to the database. So, you create one set of update code for your specific application and then cut/paste + change one line (the DTO name) for all the other versions.

I personally work with ASP.NET Core, so my examples are from that, but it will work with any NET Core type of application (I do know one person have used this libary with WPF).

Limitations with EF Core 5 and beyond

  • The ILinkToEntity<TEntity> interface can't handle an entity class mapped to a multple tables.

Code examples of using EfCore.GenericServices

I personally work with ASP.NET Core, so my examples are all around ASP.NET Core, but EfCore.GenericServices will work with any NET Core type of application (I do know one person have used this libary with WPF).

ASP.NET Core MVC - Controllers with actions

The classic way to produce HTML pages in ASP.NET is using the MVC approach, with razor pages. Here a simple example to show you the basic way to inject and then call the ICrudServices, in this case a simple List.

public class BookController

    private ICrudServices _service;

    public BookController(ICrudServices service)
    {
        _service = service;
    }

    public ActionResult Index()
    {
        var dataToDisplay = _service.ReadManyNoTracked<BookListDto>().ToList()
        return View(dataToDisplay);
    }
    //... etc.

ASP.NET Core - Razor Pages

Here is the code from the example Razor Page application contained in this repo for adding a review to a Book (the example site is a tiny Amazon-like site). This example shows an more complex example where I am updating the Book class that uses a Domain-Driven Design (DDD) approach to add a new review to a book. The code shown is the complete code in the AddReview.cshtml.cs class.

public class AddReviewModel : PageModel
{
    private readonly ICrudServices _service;

    public AddReviewModel(ICrudServices service)
    {
        _service = service;
    }

    [BindProperty]
    public AddReviewDto Data { get; set; }

    public void OnGet(int id)
    {
        Data = _service.ReadSingle<AddReviewDto>(id);
        if (!_service.IsValid)
        {
            _service.CopyErrorsToModelState(ModelState, Data, nameof(Data));
        }
    }

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        _service.UpdateAndSave(Data);
        if (_service.IsValid)
            return RedirectToPage("BookUpdated", new { message = _service.Message});

        //Error state
        _service.CopyErrorsToModelState(ModelState, Data, nameof(Data));
        return Page();
    }
}

NOTE: If you compare the code above with the AddPromotion or ChangePubDate updates in the same example then you will see they are identical apart from the type of the Data property.

And the ViewModel/DTO isn't anything special (see the AddReviewDto). They just need to be marked with an empty ILinkToEntity<TEntity> interface, which tells GenericServices which EF Core entity class to map to. For more security you can also mark any read-only properties with the [ReadOnly(true)] attribute - GenericServices will never try to update the database with any read-only marked property.

ASP.NET Core Web API

When using ASP.NET Web API then another companion library called EfCore.GenericServices.AspNetCore provides extension methods to help return the data in the correct form (plus other methods to allow unit testing of Web API actions using EfCore.GenericServices).

The code below comes from the example ToDoController example in the EfCore.GenericServices.AspNetCore GitHub repo.

public class ToDoController : ControllerBase
{

    [HttpGet]
    public async Task<ActionResult<WebApiMessageAndResult<List<TodoItem>>>> GetManyAsync([FromServices]ICrudServices service)
    {
        return service.Response(await service.ReadManyNoTracked<TodoItem>().ToListAsync());
    }

    [Route("name")]
    [HttpPatch()]
    public ActionResult<WebApiMessageOnly> Name(ChangeNameDto dto, [FromServices]ICrudServices service)
    {
        service.UpdateAndSave(dto);
        return service.Response();

    //... other action methods removed 
}

Technical features

The EfCore.GenericServices (NuGet, EfCore.GenericServices), is an open-source (MIT licence) netcoreapp2.0 library that assumes you use EF Core for your database accesses. It has good documentation in the repo's Wiki.

It is designed to work with both standard-styled entity classes (e.g. public setters on the properties and a public, paremeterless constructor), or with a Domain-Driven Design (DDD) styled entity classes (e.g. where all updates are done through named methods in the the entity class) - see this article for more on the difference between standard-styled entity classes and DDD styled entity classes.

It also works well with with dependancy injection (DI), such as ASP.NET Core's DI service. But does also contain a simplified, non-DI based configuration system suitable for unit testing and/or serverless applications.

NOTE: I created a similar library for EF6.x back in 2014, which has saved my many months of (boring) coding - on one project alone I think it saved 2 months out of 12. This new version contains the learning from that library, and the new DDD-enabling feature of EF Core to reimagine that library, but in a very different (hopefully simpler) way.

More Repositories

1

AuthPermissions.AspNetCore

This library provides extra authorization and multi-tenant features to an ASP.NET Core application.
C#
774
star
2

EfCoreinAction-SecondEdition

Supporting repo to go with book "Entity Framework Core in Action", second edition
C#
397
star
3

EfCore.TestSupport

Tools for helping in unit testing applications that use Entity Framework Core
C#
353
star
4

EfCoreInAction

Supporting code to go with the book "Entity Framework Core in Action"
340
star
5

PermissionAccessControl2

Version 2 of example application to go with articles on feature and data authorization
C#
276
star
6

GenericServices

GenericServices helps with building a service/application layer in a .NET based application using EF6.x
C#
245
star
7

NetCore.AutoRegisterDi

Extension method to find/register classes in an assembly into the Microsoft DI provider
C#
234
star
8

PermissionAccessControl

Example code for Authorization articles
C#
224
star
9

EfCore.GenericBizRunner

Library to run business logic when using Entity Framework Core for database accesses
C#
216
star
10

AspNetReactSamples

Template/Sample ASP.NET projects to develop/build/test React.js apps
JavaScript
174
star
11

EfCore.SoftDeleteServices

Services to provide simple soft delete and cascade soft delete in EF Core
C#
114
star
12

EfCore.SchemaCompare

Library to compare EF Core's Model of the database against a database's schema.
C#
106
star
13

Net.DistributedFileStoreCache

NET distributed cache using a json file as the shared resourse with very fast Get
C#
96
star
14

SampleMvcWebApp

A Sample MVC5 web application showing the use of GenericServices for CRUD operations
C#
75
star
15

EfCore.GenericEventRunner

A library to allow developer use events to update their database via Entity Framework Core (EF Core)
C#
67
star
16

EfCoreSqlAndCosmos

Example CQRS application using Cosmos DB with EF Core
C#
66
star
17

BookApp.All

Example of applying an modular monolith approach to building apps. This version contains the whole app in one solution
C#
50
star
18

EfCore.GenericServices.AspNetCore

Converts EFCore.GenericServices and EfCore.GenericBizRunner statuses to ASP.NET Core formats
C#
49
star
19

EfSchemaCompare

EfSchemaCompare.EF6 allows you to compare Entity Framework's database modal with an actual SQL database.
C#
44
star
20

RunStartupMethodsSequentially

A .NET library that runs methods within a locked state on startup. This is useful if you want to migrate or seed a database on an web application that has multiple instances.
C#
32
star
21

EfCore.SoftDeleteServices-Old

Services to provide simple soft delete and cascade soft delete in EF Core
C#
29
star
22

GenericServices.StatusGeneric

Implements the "return a status" pattern - useful for code that can return errors
C#
28
star
23

SampleMvcWebAppComplex

A more complex MVC application showing the use of GenericServices with the AdventureWorksLT2012 database.
C#
26
star
24

Net.LocalizeMessagesAndErrors

This library provides extra code to make it easier to support in different languages in your .NET application
C#
18
star
25

MvcUsingBower

Applying Visual Studio's Bower/Grunt tools to a ASP.NET MVC application. See
JavaScript
16
star
26

PermissionsOnlyApp

C#
15
star
27

DDDExampleCode

Example code to go with my talk and article on DDD
C#
13
star
28

MultiProgPackTool

https://www.thereformedprogrammer.net/evolving-modular-monoliths-2-breaking-up-your-app-into-multiple-solutions/#how-to-create-a-nuget-packages
C#
9
star
29

SimpleMessageBroker

C#
5
star
30

Ef6BookApp

C#
4
star
31

AspNetCore.MultipleHostedService

C#
3
star
32

AuthP.CustomDatabaseExamples

C#
2
star
33

BookApp.Books

Part of the evolving Modular Monalith
C#
2
star
34

TryAspNetCoreMigrate

C#
2
star
35

BookApp.Main

C#
2
star
36

TestSupportSchema

C#
1
star