


Describe in detail the implementation method of Entity Framework custom paging effect
This article mainly introduces in detail the custom paging effect based on Entity Framework, the general implementation of additions, deletions and modifications. It has certain reference value. Interested friends can refer to it
Introduction
I previously wrote a paging implementation based on Dapper, and now I will write a paging implementation based on Entity Framework, as well as a universal implementation of additions, deletions and modifications.
Code
How to run the example
Still as before:
1. Clone the code first and decompress Database.7z
2 in Database. Attach it to Sql Server LocalDB. If you are not using LocalDB of Sql Server, you need to change the connection string in App.Config.
3. Ctrl + F5, run the sample program.
Repository base class - query
Common\AbstractRepository.cs is the base class of Repository, which implements addition, deletion and modification Some methods of query, for example:
public virtual Tuple<IEnumerable<T>, int> Find(Expression<Func<T, bool>> criteria , int pageIndex , int pageSize , string[] asc , string[] desc , params Expression<Func<T, object>>[] includeProperties)
This method is one of the AbstractRepository query methods, used for custom paging query, where criteria is an expression, as the query Conditions, parameters pageIndex, pageSize, asc, desc are paging related parameters;
About multiple tables (associated tables):
includeProperties are the tables associated with Join when there are multiple tables. Because EF defaults to Lazy Loading, the associated tables are not loaded immediately by default, so sometimes if you are not careful when writing code, you may loop through n word tables in a for loop. Use the includeProperties parameter to join the related table during query.
Repository base class - addition, deletion and modification
AbstractRepository has implemented the addition, deletion and modification method using generics:
public virtual T Create(T entity)
public virtual T Update(T entity)
public virtual T CreateOrUpdate(T entity)
public virtual void Delete(TId id)
In addition, about the implementation of transaction , I used the Unit of Work mode, multiple Repositories share a DBContext, about UOW, please find it in Common\UnitOfWork.cs.
When calling UOW, it is basically similar to this:
var uow = new EFUnitOfWork(); var repo = uow.GetLogRepository(); repo.Create(new Log { LevelId = 1, Thread = "", Location = "Manual Creation", Message = "This is manually created log.", CreateTime = DateTimeOffset.Now, Date = DateTime.Now }); uow.Commit();
Get one or more Repository from UnitOfWork, share DBContext, and perform addition, deletion and modification operations. Finally uow unifies SaveChanges.
Derived classes of Repository
Since there is already AbstractRepository, many methods of adding, deleting, modifying and checking are implemented, so derived classes, such as LogRepository in the sample project It can basically become very simple, mainly implementing some specific business logic. In the example project, because there is no special business logic, it will be very simple:
public class LogRepository : AbstractRepository<Log, int> { public LogRepository(EFContext context) : base(context) { } }
About Entity generation
I prefer Database First implementation, first design the database, and then use edmx reverse engineering to generate POCO. You can refer to the relevant files in the Entity directory.
Of course, if you like Code First, there is no problem, the implementation of this article still applies.
Use Logging logs to track EF SQL
When using Entity Framework, it is best to pay attention to the SQL generated by EF, so that it can be discovered during the development stage There are some potential performance issues to avoid being overwhelmed in the production environment:)
In Common\EFContext.cs, there is a configuration item EnableTraceSql. If it is true, then the SQL generated by EF will be recorded by nlog. I configured nlog logs to the database. That is to say, when you run the sample project, every time you query, a new log record will be added, and the content is the SQL generated during the query:
Specification Pattern
In the query method, there is an overload that accepts an ISpecification example. This implementation can effectively control the business logic. For interfaces written to be called by others, you can Clearly determine the query parameters, for example:
public class LogSearchSpecification : ISpecification<Log> { public string LevelName { get; set; } public string Message { get; set; } public Expression<Func<Log, bool>> ToExpression() { return log => (log.Level.Name == LevelName || LevelName == "") && (log.Message.Contains(Message) || Message == ""); } public bool IsSatisfiedBy(Log entity) { return (entity.Level.Name == LevelName || LevelName == "") && (entity.Message.Contains(Message) || Message == ""); } }
Then, the code that calls this query method can clearly know that my query conditions are LevelName and Message. As for LevelName, it is equal to And the Message is Like is implemented in LogSearchSpeficiation, which is well encapsulated.
Finally
This set of implementations has been slowly accumulated over the past few years and has been practiced, so it should be used as a certain reference. Of course, in In specific projects, you can use some DI to get the Repository, etc. This is beyond the scope of this article. You can use it freely. I hope it can be helpful to everyone. Thank you.
The above is the detailed content of Describe in detail the implementation method of Entity Framework custom paging effect. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

An avatar on Netflix is a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

How to customize background image in Win11? In the newly released win11 system, there are many custom functions, but many friends do not know how to use these functions. Some friends think that the background image is relatively monotonous and want to customize the background image, but don’t know how to customize the background image. If you don’t know how to define the background image, the editor has compiled the steps to customize the background image in Win11 below. If you are interested If so, take a look below! Steps for customizing background images in Win11: 1. Click the win button on the desktop and click Settings in the pop-up menu, as shown in the figure. 2. Enter the settings menu and click Personalization, as shown in the figure. 3. Enter Personalization and click on Background, as shown in the picture. 4. Enter background settings and click to browse pictures

A Venn diagram is a diagram used to represent relationships between sets. To create a Venn diagram we will use matplotlib. Matplotlib is a commonly used data visualization library in Python for creating interactive charts and graphs. It is also used to create interactive images and charts. Matplotlib provides many functions to customize charts and graphs. In this tutorial, we will illustrate three examples to customize Venn diagrams. The Chinese translation of Example is: Example This is a simple example of creating the intersection of two Venn diagrams; first, we imported the necessary libraries and imported venns. Then we create the dataset as a Python set, after that we use the "venn2()" function to create

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.

CakePHP is a powerful PHP framework that provides developers with many useful tools and features. One of them is pagination, which helps us divide large amounts of data into several pages, making browsing and manipulation easier. By default, CakePHP provides some basic pagination methods, but sometimes you may need to create some custom pagination methods. This article will show you how to create custom pagination in CakePHP. Step 1: Create a custom pagination class First, we need to create a custom pagination class. this
![SCNotification has stopped working [5 steps to fix it]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

The iOS 17 update for iPhone brings some big changes to Apple Music. This includes collaborating with other users on playlists, initiating music playback from different devices when using CarPlay, and more. One of these new features is the ability to use crossfades in Apple Music. This will allow you to transition seamlessly between tracks, which is a great feature when listening to multiple tracks. Crossfading helps improve the overall listening experience, ensuring you don't get startled or dropped out of the experience when the track changes. So if you want to make the most of this new feature, here's how to use it on your iPhone. How to Enable and Customize Crossfade for Apple Music You Need the Latest
