Detailed Entity Framework custom paging effect implementation method

Source: Internet
Author: User
Tags sql using
This article mainly for you in detail on the basis of the Entity Framework custom paging effect, adding and removing the general implementation of the change, with a certain reference value, interested in small partners can refer to

Brief introduction

Before writing a paging implementation based on Dapper, now write a paging implementation based on the Entity Framework, as well as the general implementation of adding and deleting.

Code

How to run the sample

Still the same as before:

1. First clone under Code, in the database decompression database.7z

2. Attach to SQL Server localdb. If you are not using SQL Server LOCALDB, 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 realizes some methods of adding and deleting, 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 to customize the paging query, where criteria is an expression, as a condition of the query, Parameters pageindex, pageSize, ASC, desc for paging related parameters;

About multiple tables (associated tables):

Includeproperties is a table that is associated with a join at multiple tables. Because EF defaults to lazy Loading, the associated table is not loaded immediately by default, so sometimes it is possible to iterate through the N-Word table in the for loop if the code is not carefully written. To includeproperties parameters, you can join the associated table at query time.

Repository base class-additions, deletions and modifications

Abstractrepository has been implemented using generics to modify the method of adding and deleting:

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, regarding the implementation of transaction, I used the unit of work mode, multiple repository share a dbcontext, about UOW, please find 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 = "The is manually create D log. ",  createtime = Datetimeoffset.now,  Date = DateTime.Now}); Uow.commit ();

From Unitofwork to get one or more repository, share dbcontext, do delete and change operation, and finally UOW Unified SaveChanges.

Derived classes for repository

Because of the abstractrepository, there are many ways to make additions and deletions, so derived classes, such as the logrepository in the sample project, can become very simple, mainly implement some specific business logic, in the example project, because there is no special business logic, So it will be simple:


public class Logrepository:abstractrepository<log, int>  {public    logrepository (Efcontext context)      : Base (context)    {    }  }

About the generation of entity

I prefer the database first implementation, design databases, and then use the EDMX reverse engineering, generate Poco. You can refer to the relevant files under the entity directory.

Of course, if you like code first, there is no problem, and the implementation of this article still applies.

Tracking EF SQL using logging logs

When using the Entity Framework, it's a good idea to focus on the SQL generated by EF, so you can find some potential performance issues during the development phase to avoid being in a production environment:)

In Common\efcontext.cs, there is a configuration item enabletracesql, if true, so the SQL generated by EF will be recorded nlog. I configured the Nlog log to the database. That is, when you run the sample project, each query adds a new log record, which is the SQL generated at the time of the query:

Specification Pattern

In the query method, there is an overload is to accept an ispecification example, such an implementation can effectively control the business logic, for the interface called by others, you can explicitly determine the query parameters, such as:


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 be clearly known that my query condition is levelname and message, as for levelname is equal to and the message is like is implemented in the logsearchspeficiation, so good encapsulation.

At last

This set of implementation is gradually accumulated over the past few years, is through practice, so should be used as a certain reference, of course, in specific projects, you can use some di to get repository, etc., not in the scope of this discussion, we can freely play, I hope you can help, thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.