1.数据操作封装
- 1.1概述
在习惯使用ADO.NET数据库访问与操作封装,通常写DataHelper/SQLHelper类。到如今ORM大行其道,我们该爱上存储库模式来封装操作。当然,为了顾及初学者,在封装方法时,还是教学方式,一步步地来,最终重构成通用可重用的代码。所以一开始先不用泛型及写一些扩展方法。
- 1.2新增目录
- 1.3代码
面向接口编程方式,先定义接口:
using BlogASPNET5.Entity.Accounts; using System.Collections.Generic; namespace BlogASPNET5.Repository.Interfaces { public interface IUserRepository { IEnumerable<User> GetUsers(); User GetUser(int id); User CreateUser(User user); User UpdateUser(int id, User user); bool DeleteUser(int id); } }
接口实现:
using BlogASPNET5.Repository.Interfaces; using BlogASPNET5.Entity.Accounts; using System.Collections.Generic; using BlogASPNET5.Repository.Contexts; using System.Linq; namespace BlogASPNET5.Repository.Implements { public class UserRepository :IUserRepository { //应该构造函数实例化,并注入DI容器,单例模式 EFContext db =new EFContext(); public User CreateUser(User user) { db.Users.Add(user); db.SaveChanges(); return user; } public bool DeleteUser(int id) { var user = db.Users.Where(u => u.Id == id).First(); db.Users.Remove(user); if (db.SaveChanges() > 0) { return true; } return false; } public User GetUser(int id) { var user = db.Users.Where(u => u.Id == id).First(); return user; } public IEnumerable<User> GetUsers() { return db.Users.AsEnumerable(); } public User UpdateUser(int id, User us) { var user = 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(); } return user; } } }
- 1.4调用
在控制台程序测试:
using BlogASPNET5.Repository.Implements; using BlogASPNET5.Repository.Interfaces; using System; namespace BlogASPNET5.ConsoleApp { public class Program { public void Main(string[] args) { //接口引用具体实例,显然没有解耦 //ASP.NET 5已经内置DI,很方便配置,后文再说 IUserRepository ur = new UserRepository(); var list = ur.GetUsers(); foreach (var item in list) { Console.WriteLine(item.Name); } Console.ReadLine(); } } }
2.小结
本篇代码其实很烂,但从简入繁的过程,却是很容易理解。(回头再续下一篇……)
时间: 2024-11-06 13:42:27