Entity Framework Repository Mode

Source: Internet
Author: User

before repository mode

If we were to design a "C (Increase), R (read), U (Modify), D (delete)" Four operations for each entity class with the most primitive ef.

First: take a look at the query, for the entity class simple query operations, each time this process will have a lot of code to repeat the very similar code snippets.

  using(vardb =NewEfcontext ("Efcontext"))            {                varPersons = db. Persons.where (t = T.personname = ="Aehyok"). OrderByDescending (t =T.personid).                ToList (); foreach(varPinchpersons) {Console.WriteLine ("The personname is {0} and age {1}", P.personname, p.age); }} console.readline ();

The second one: for the add operation of the entity class.

            using(vardb =NewEfcontext ()) {                varStephen =NewPerson {PersonName="aehyok0001", Age= -, Address="Shenzhen Nanshan", Email="[email protected]"                }; Db.                Persons.add (Stephen); Db.                Persons.attach (Stephen); Db. Entry (Stephen). State= entitystate.unchanged;////Same as above db. Persons.attach (Stephen); the effect is the same                varJeffrey =NewPerson {PersonName="aehyok0002", Age= -, Address="Shenzhen Baoan", Email="[email protected]"                }; Db. Entry (Jeffrey). State=entitystate.added; Db.            SaveChanges (); }

Third: Similarly, the delete operation is as follows.

  using (varnew  efcontext ())            {                var4). FirstOrDefault ();                Db. Persons.remove (person);                Db. SaveChanges ();            }

Fourth : Similarly, the modification operation is as follows.

        using (varnew  efcontext ())            {                var4). FirstOrDefault ();                Db. Persons.remove (person);                Db. SaveChanges ();            }

The above is based on an entity class simple curd operation, of course, the query is changeable. In the data access layer, we can specifically for each class to encapsulate the business processing class, but where the class and class between the same or similar code snippet too much, for the coder, it is a waste of time, the same code, in the different use of the project, make multiple copies to modify several code fields can be used, So why don't we do a simple encapsulation to make this process easier, and make our code more elegant, making maintenance easier for developers and easier to scale. Based on the above considerations, we draw out our repository design pattern.

Repository design mode

In the Enterprise architecture model, the translator translates repository into a resource library. Give the following description: Coordinate between the domain and the data map layer by using a similar collection of interfaces to access the domain object.

Then, based on the Rspository model, the data access layer is nothing more than the data to be modified, including the increase, deletion, change, etc. we can abstract out to write a common interface or abstract class to define these methods, and a base class to implement these methods, so that the base class derived from the subclass will inherit the increment, delete, change these methods, This avoids the need for each entity to implement these methods repeatedly. In a nutshell, the data access layer is better reused through interface generics and ORM.

Repository Code implementation

1.EF instance data Manipulation context object

Primarily initializes the database and sets up the database for Automatic Updates

   Public classEfcontext:dbcontext { PublicEfcontext ():Base("default") {Database.setinitializer<EFContext> (NewMigratedatabasetolatestversion<efcontext,efdbmigrationsconfiguration>()); }         PublicDbset<member> Members {Get;Set; }  PublicDbset<score> Scores {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); Modelbuilder.entity<Member> (). Hasmany (b =b.scores); }    }    Internal Sealed classEfdbmigrationsconfiguration:dbmigrationsconfiguration<efcontext>    {         Publicefdbmigrationsconfiguration () {automaticmigrationsenabled=true;//any changes to the model class will automatically update the DB directlyautomaticmigrationdatalossallowed =true;//values that can be accepted for data loss during automatic migration        }    }

2.BaseEntity class

The BaseEntity class defines the public properties of all participating data manipulation entities, so we define the class as an abstract class, as a base class for derived classes.

 Public Abstract class baseentity    {        [Key]        publicgetset;}          Public Get Set ; }          Public baseentity ()        {            = guid.newguid ();             = datetime.now;        }    }

The lowest-level interface implementation in 3.Repository mode irepository

We extract the common operating parts of the entities as irepository interfaces, such as the usual additions, deletions, and modifications.

 Public InterfaceIrepository<tentity>wheretentity:baseentity {DbSet<TEntity> Entities {Get; } //Add a single entity        intInsert (TEntity entity); //Add multiple Entities        intInsert (ienumerable<tentity>entities); //Update Entity        intUpdate (TEntity entity); //Delete        intDelete (ObjectID); //get entities based on primary keyTEntity Getbykey (Objectkey); }

The definition of the interface method, which is based on the business in the project, defines the method that adapts itself. Have a certain degree of flexibility

We find that the generic tentity of the interface has a constraint to inherit baseentity,baseentity is to extract the public attributes of the entity, such as: Id (primary key), CreateDate (creation time), etc.

interface-based abstract class Efrepositorybase in 4.Repository mode

We use an abstract class efrepositorybase to implement the methods in the interface, so that derived classes have methods defined in the interface and prevent Efrepositorybase from being instantiated directly.

  Public Abstract classEfrepositorybase<tentity>:irepository<tentity>wheretentity:baseentity {efcontext EF=NewEfcontext ();  PublicDbset<tentity>Entities {Get{returnEf. Set<tentity>(); } }         Public intInsert (TEntity entity) {Entities.add (entity); returnEF.        SaveChanges (); }         Public intInsert (ienumerable<tentity>entities)            {Entities.addrange (entities); returnEF.        SaveChanges (); }         Public intUpdate (TEntity entity) {EF. Entry (entity). State=entitystate.modified; returnEF.        SaveChanges (); }         Public intDelete (ObjectID) {///Delete operation Implementation            return 0; }         PublicTEntity Getbykey (Objectkey) {            returnEntities.find (key); }    }

5. Simple call

You can see that the call processing is done.

Summarize

Entity Framework Repository Mode

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.