1. Data Operation Package
In the habit of using the ADO database access and operation encapsulation, usually write the Datahelper/sqlhelper class. By now the ORM is on its way, we should fall in love with the repository pattern to encapsulate the operation. Of course, in order to take into account the beginner , in the encapsulation method, or the teaching method , step by step, eventually re-form the common reusable code. So start without generics and write some extension methods first.
Interface-oriented programming, first define interface :
using BlogASPNET5.Entity.Accounts; using System.Collections.Generic; namespace blogaspnet5.repository.interfaces{ public interface Iuserrepository {Ienumerab Le <user> Getusers (); User GetUser ( int ID); User CreateUser (user user); User UpdateUser ( int ID, user user); bool deleteuser (int ID); }}
Interface Implementation :
usingBlogASPNET5.Repository.Interfaces;usingBlogASPNET5.Entity.Accounts;usingSystem.Collections.Generic;usingBlogASPNET5.Repository.Contexts;usingSystem.Linq;namespaceblogaspnet5.repository.implements{ Public classUserrepository:iuserrepository {//The constructor should be instantiated and injected into the Di container, a singleton patternEfcontext db =NewEfcontext (); Publicuser CreateUser (user user) {db. Users.add (user); Db. SaveChanges (); returnuser; } Public BOOLDeleteUser (intID) {varuser = db. Users.where (U = u.id = =ID). First (); Db. Users.remove (user); if(Db. SaveChanges () >0) { return true; } return false; } PublicUser GetUser (intID) {varuser = db. Users.where (U = u.id = =ID). First (); returnuser; } PublicIenumerable<user>getusers () {returndb. Users.asenumerable (); } PublicUser UpdateUser (intID, User us) { varuser = db. Users.where (U = u.id = =ID). First (); if(User! =NULL) {User. Name=us. Name; User. Password=us. Password; User. Gender=us. Gender; User. Role=us. Role; Db. SaveChanges (); } returnuser; } }}
In the console program test:
usingBlogASPNET5.Repository.Implements;usingBlogASPNET5.Repository.Interfaces;usingSystem;namespaceblogaspnet5.consoleapp{ Public classProgram { Public voidMain (string[] args) { //interfaces refer to specific instances and are clearly not decoupled//the ASP. NET 5 has built-in Di, very convenient to configure, after the articleiuserrepository ur =Newuserrepository (); varList =Ur. Getusers (); foreach(varIteminchlist) {Console.WriteLine (item. Name); } console.readline (); } }}
2. Summary
This code is really bad, but the process of simplifying into the complex , but it is very easy to understand. (Go back to the next article ...) )
Play to ASP. 5: Data operation Encapsulation (i)