


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!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

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.


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

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
