Entity Framework custom paging effect implementation tutorial
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
Let’s get the code first: https://github.com/jinweijie/EF.GenericRepository
How to Run the example
Still as before:
1. Clone the code first and decompress Database.7z in Database
2. Attach to On 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.
The above is the detailed content of Entity Framework custom paging effect implementation tutorial. For more information, please follow other related articles on the PHP Chinese website!

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools
