نموذج أساسي لـ Nano ASP.NET SaaS
بيانات اعتماد المسؤول (جميع المستأجرين): admin@email.com / Password123!
تتم إعادة تعيين البيانات النموذجية كل ساعة

نمط المستودع مع المواصفات في ASP.NET Core | دليل مجاني + GitHub

رايان لويس
مارس 17, 2025

The repository pattern has been at the center of heated debate around the internet since it was introduced back in the ancient times as part of Domain-Driven Design.

The original goal of repository pattern was to provide a layer of abstraction over data persistence operations. This makes the architecture decoupled so that in the future should you ever want to switch to a different ORM, you can do so with minimal disruption. Let’s get real for a moment, does anyone ever do that? Does anyone ever say halfway through developing an ASP.NET application, “hey let’s use Dapper بدلاً من إطار عمل الكيانات”? No, because you make that decision knowing what kind of app you are building from the start.

Practicality aside, implementing the repository pattern does decouple the architecture. That is, until إطار عمل الكيانات came out and made things totally redundant. Entity Framework, the official ORM from Microsoft, is the repository pattern on its own. All those مجموعات قواعد البيانات that provide mapping for new entities are repositories and the context is the unit of work.

So let’s not use repository pattern! End of article.

Well, sort of. How about, let’s not use the traditional implementation of repository pattern (repository per entity) but instead look at how we can use a generic repository مع specification pattern to make our architecture awesome.

In a generic repository pattern, we can handle low-level repetitive code like pagination و DTO mapping, while keep things flexible with specification. Also, if you plan to build your application with something like clean-architecture, then the decoupled nature is still nice to have.

The complete code for this tutorial is available from the GitHub هنا

If you are in the business of building apps, then check out the نص قياسي عن تقنية النانو. The patterns and practices you will learn in this tutorial are quite similar, except that the نص قياسي عن تقنية النانو contains so much more! You can create entire SaaS solutions, controller, and services from the command line. Not to mention, you support our efforts J

First let’s look at what not to do, the repository per entity approach; aka the traditional way of implementing the repository pattern. It involves creating a repository class per each entity in your application. So for example, if you have a المنتج entity in your application, you would create a ProductRepository class which would contain CRUD operations, plus any specific product operations

عام فئة ProductRepository
{
    خاص للقراءة فقط ApplicationDbContext _context;

    عام ProductRepository(ApplicationDbContext context)
    {
        _السياق = السياق;
    }

    // get all
    عام غير متزامن المهمة<IEnumerable<المنتج>> GetListAsync()
    {
        قائمة<المنتج> قائمة = انتظار _السياق.المنتجات.ToListAsync();

        العودة قائمة;
    }

    // get by supplier
    عام غير متزامن المهمة<IEnumerable<المنتج>> GetListBySupplierAsync(Guid supplierId)
    {
        قائمة<المنتج> قائمة = انتظار _السياق.المنتجات.أين(x => x.المورد.المعرّف == supplierId).ToListAsync();

        العودة قائمة;
    }

    // create, update, delete, etc...

}

Another entity in your application like المورد could look similar but with its own specific operations which are quite rigid.

This is the simple example of the repository pattern you find all over the internet. It just creates so much extra code. Whenever you have a slight variation of a احصل على request, you are forced to create a new method. In a short time, your app will contain tons of repositories with a large number of methods.

As the name implies, with the generic repository pattern, we’ll only have one repository class which will be used by all entity types. For the ‘entity specific operations’, we’ll use specification pattern together with the repository pattern so that this one generic repository with standard methods can accommodate any kind of data query. All of our methods will be asynchronous.

Let’s start with the simplest method إنشاء so we can understand the generic signature. Eventually our generic repository will contain all the standard CRUD operations plus a few extras like pagination. To get things rolling, create a منشئ and inject the application context.

        خاص للقراءة فقط ApplicationDbContext _context;

        عام RepositoryAsync(ApplicationDbContext السياق)
        {
            _السياق = السياق;
        }
        
        
        // create method
        عام غير متزامن المهمة<T> CreateAsync<T, TId> (T entity)
        where T : الكيان الأساسي<TId>
        {
            _ = انتظار _السياق.Set<T>().AddAsync(الكيان);
            العودة الكيان;

        }

Our T should be represented by a base entity class which can use any kind of type as an ID, in this case we will use a Guid. There’s not much variation in a typical إنشاء request, so we won’t need any specification pattern yet. If we were to use this repository method in some application service, this is how we would do it. By the way, you can download the finished code from the GitHub repo to see everything, including that within the common classes like الكيان الأساسي, Response, etc.

        // create new Product
        عام غير متزامن المهمة<Response<Guid>> CreateProductAsync(طلب إنشاء المنتج (CreateProductRequest))
        {
            جرب
            {
                Product response = انتظار _repository.CreateAsync<المنتج, Guid> (طلب); 
                _ = انتظار _repository.SaveChangesAsync(); // save changes to db
                العودة Response<Guid>.Success(الرد.المعرّف); // return id
            }
            القبض (استثناء ex)
            {
                العودة Response<Guid>.Fail(مثال.رسالة);
            }
        }

Unlike إنشاء, in a احصل على method there usually is some variance, and therefore we would need the flexibility of specifications. We may want to pass some kind of filter criteria depending on our situation. In the traditional repository per entity approach, we would create a separate method for each scenario like GetProductsByName, GetProductsByType and drive ourselves mad with code. With the specification pattern, we will instead pass a specification. The specification would then be evaluated within the generic repository. This will allow our methods to be super flexible and allow us to build any kind of query.

Using specification pattern is the key to making everything work within a generic repository, otherwise our generic repository would be too rigid to accommodate different kinds of queries.

With specification pattern, the idea is to pass generic expressions from your services and build up a query within the repository. At minimum you will need a base specification class to construct queries using LINQ مع dynamic expressions. These specifications are then converted to a query by a specification evaluator class within the repository.

As you might imagine, the evaluator class, base specification and any helper methods working to make the specification pattern work can get complex quickly. They need to handle all kinds of query types like the expression itself plus includes, ordering, then include, sorting, etc. Earlier versions of the Nano Boilerplate had a home-rolled implementation of the specification pattern, which admittedly resulted in a lot of code and was a bit confusing. Luckily for us though, someone made the Ardalis Specification NuGet library which does all of this for us!

الـ Ardalis Specification package is complete package, able to handle every kind of query method supported by Entity Framework.

To get working with the specification pattern in ASP.NET, install the Ardalis Specification package. You’ll also want to get the Ardalis Entity Framework Core package since we’re going to use Entity Framework. With this package installed, Specification classes can be used to build queries. These ORM-agnostic directives will get passed to the repository methods where a SpecificationEvaluator class will translate them into queries. The نص قياسي عن تقنية النانو currently uses the Ardalis Specification in the same way we will do here.

The specification pattern will be used in all our methods that retrieve data.

Add a using statement for Ardalis Specification

Let’s make a احصل على method to retrieve a list of T entity. Write your code like this

        // get all, return non-paginated list of domain entities
        عام غير متزامن المهمة<IEnumerable<T>> GetListAsync<T, TId> (ISpecification<T> specification = null, CancellationToken cancellationToken = default) where T : الكيان الأساسي<TId>
        {

            IQueryable<T> استعلام;
            إذا (specification == null)
            {
                استعلام = _السياق.Set<T>().AsQueryable();
            }
            وإلا
            {
                استعلام = SpecificationEvaluator.Default.GetQuery(
                  استعلام: _السياق.Set<T>().AsQueryable(),
                  specification: specification);
            }
            قائمة<T> النتيجة = انتظار استعلام.ToListAsync(cancellationToken);
            العودة النتيجة;
        }

Notice that specification parameter is optional, so in the case that no specification is sent, the full list of T entity will be returned. In the case that a specification is sent, a query will be generated using the SpecifcationEvaluator. If we were to dive into what is happening in the SpecificationEvaluator class, we’d find it to be pretty complex. Luckily we don’t need to worry about it.

In an application service like المنتج service, we can inject the repository and use the GetListAsync method. We’ll pass it a specification to build a query.

        // get full List
        عام غير متزامن المهمة<Response<IEnumerable<ProductDTO>>> GetProductsAsync(سلسلة keyword = "")
        {
            ProductSearchList specification = جديد(keyword); // ardalis specification
            IEnumerable<ProductDTO> قائمة = انتظار _repository.GetListAsync<المنتج, ProductDTO, Guid> (specification); // full list, entity mapped to dto
            العودة Response<IEnumerable<ProductDTO>>.Success(قائمة);
        }

Our specification might look like this:

 عام فئة ProductSearchList : Specification<المنتج>
 {
     عام ProductSearchList(سلسلة? keyword = "")
     {
         // filters
         إذا (!سلسلة.IsNullOrWhiteSpace(keyword))
         {
             _ = Query.أين(x => x.الاسم.Contains(keyword));
         }

         _ = Query.OrderByDescending(x => x.Priority); // default sort order
     }
 }

Perhaps we want search an optional keyword and provide some default ordering by Priority. For this we can create a specification called ProductSearchList. If we had related entities we could add Includes أو ThenIncludes with lambda expressions to eager load the data.

One of the really useful things about specification pattern is that you can encapsulate the query logic in the specification classes and name them appropriately. As your project grows into a sprawling monstrosity, this is helpful in keeping things understandable, plus these classes are reusable.

بالنسبة إلى حذف و تحديث, it’s not really necessary to handle a specification. You might want to create methods for Get by ID instead of a list, Exists to check if an entity is present, and perhaps a Create Range, but that’s up to you. These would make sense to have specification.

Adding a Get method for paginated results method would be quite useful within the repository. This way pagination logic won’t need to be repeated anywhere else. The implementation of a pagination method will depend on how your front-end tables expect the data to be shaped. Since we are getting data, this method would also need a specification parameter. Here is how a pagination method could look if you were using Tanstack Table v8, a very popular front-end table library (used in the Nano Boilerplate). TanStack Table is framework agnostic, so you can use it in a React, Vue, or Angular project all the same.

// return paginated list of mapped dtos -- format specific to Tanstack Table v8 (React, Vue)
عام غير متزامن المهمة<PaginatedResponse<TDto>> GetTanstackPaginatedResultsAsync<T, TId> (int pageNumber, int pageSize, ISpecification<T> specification = null, CancellationToken cancellationToken = default)
    where T : الكيان الأساسي<TId>
{

    IQueryable<T> استعلام;
    إذا (specification == null)
    {
        استعلام = _السياق.Set<T>().AsQueryable();
    }
    وإلا
    {
        استعلام = SpecificationEvaluator.Default.GetQuery(
          استعلام: _السياق.Set<T>().AsQueryable(),
          specification: specification);
    }

    قائمة<TDto> pagedResult;
    int recordsTotal;
    جرب
    {
        recordsTotal = انتظار استعلام.CountAsync(cancellationToken);
        pagedResult = انتظار استعلام
            .Skip((pageNumber - 1) * pageSize).Take(pageSize)
            .ToListAsync(cancellationToken);
    }
    القبض (استثناء ex)
    {
        رمي جديد استثناء(مثال.رسالة);
    }

    العودة جديد PaginatedResponse<T> (pagedResult, recordsTotal, pageNumber, pageSize);
}

As you can see, it’s the same as with the regular Get methods where we pass the specification to build a query. There are additional parameters to specify page size و starting index. The return format is also different.

It’s worth mentioning that there is a repository class included within the Ardalis Specification package. While you could use it, it’s pretty basic, with no pagination or DTO mapping (which we will see next) so you are better off creating your own (or just stealing this code).

Finally to make our repository class even more robust, we can add override methods for all of the methods that return data. The additional methods will give us the option to retrieve data as domain entities أو منظمات تجارة المخدرات.

Install the AutoMapper library from Nuget. This is a popular library that can take a lot of the busy work out of translating domain entities to DTO. Add a using statement for the package in the repository class and inject the mapper via the constructor.

Here we can see the code for the Get list method. It’s the same as the regular method except that we pass it an additional type for the DTO in the signature.

        // get all, return non-paginated list of mapped dtos
        عام غير متزامن المهمة<IEnumerable<TDto>> GetListAsync<T, TDto, TId> (ISpecification<T> specification = null, CancellationToken cancellationToken = default) where T : الكيان الأساسي<TId>
            where TDto : IDto
        {

            IQueryable<T> استعلام;
            إذا (specification == null)
            {
                استعلام = _السياق.Set<T>().AsQueryable();
            }
            وإلا
            {
                استعلام = SpecificationEvaluator.Default.GetQuery(
                  استعلام: _السياق.Set<T>().AsQueryable(),
                  specification: specification);
            }

            قائمة<TDto> النتيجة = انتظار استعلام
                .ProjectTo<TDto> (_mapper.ConfigurationProvider)
                .ToListAsync(cancellationToken);

            العودة النتيجة;
        }

Using AutoMapper’s projection method, we can pass the mapping configuration. A list of DTOs will be returned instead of domain entities. You’ll need to create a class somewhere that implements the mapping profiles for all your entities. Here I’ve created a class and done my DTO mapping like this for the المنتج entity.

    عام فئة MappingProfiles : Profile // automapper mapping configurations
    {
        عام MappingProfiles()
        {

            // product mappings
            _ = CreateMap<المنتج, ProductDTO>();
            _ = CreateMap<طلب إنشاء منتج, المنتج>();
            _ = CreateMap<تحديث طلب المنتج, المنتج>();

            // add new entity mappings here...
        }
    }

Apply this same idea across all the Get methods and pagination to offload the majority of your mapping workload to the repository.

With all this in place our repository is pretty capable! In the attached code you can see the full solution with all the methods; pagination and DTO mapping included. Hopefully this gives you a clear understanding of how to use generic repository pattern in ASP.NET core web applications.

Feel free to use this code in your own projects or check out the Nano Boilerplate for a more complete solution. With the نص قياسي عن تقنية النانو, you can generate full SaaS project customizable from the command line. If you’ve followed along in this tutorial, you will already be familiar with the repository pattern in Nano, but there are many more features like multi-tenancy, clean-architecture, authentication / authorization, user management, and multiple UI options which can save you tons of time when kick starting new projects.

Thanks for reading, good luck with your projects.

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

هل تحتاج إلى نموذج ASP.NET لإنشاء مشروع MVP القادم؟
تعرّف على مشروع «Nano ASP.NET» النموذجي لخدمات البرمجيات كخدمة (SaaS) متعددة المستأجرين، ووفّر أسابيع أو أشهر من وقت التطوير.
مزيد من المعلومات