.net core webapi搭建(3)Code first+拆层三层+仓储
将项目拆层
我们要 将项目拆分成
Infrastructure 基础层
Core 核心层
Utility 工具
我们想在就把项目拆分开,拆分后的结构如下:
创建BaseEntity
public abstract class EntityBase { //自增长逐渐 public int Id { get; set; } //是否删除 今后肯定要软删除的 public bool Deleted { get; set; } //创建时间 public DateTime CreateTime { get; set; } //删除时间 public DateTime? DeleteTime { get; set; } }
创建IRepository
public interface IRepository<T> where T : EntityBase { /// <summary> /// 通过自增长主键获取唯一Model /// </summary> /// <param name="id"></param> /// <returns></returns> Task<T> GetByIdAsync(int id); /// <summary> /// 通过自增长主键获取唯一Model(包含字段) /// </summary> /// <param name="id"></param> /// <returns></returns> Task<T> GetByIdAsync(int id, params Expression<Func<T, object>>[] includes); Task<T> GetSingleAsync(Expression<Func<T, bool>> criteria); Task<T> GetSingleAsync(Expression<Func<T, bool>> criteria, params Expression<Func<T, object>>[] includes); IEnumerable<T> ListAll(); Task<List<T>> ListAllAsync(); IEnumerable<T> List(Expression<Func<T, bool>> criteria); Task<List<T>> ListAsync(Expression<Func<T, bool>> criteria); IEnumerable<T> List(Expression<Func<T, bool>> criteria, params Expression<Func<T, object>>[] includes); Task<List<T>> ListAsync(Expression<Func<T, bool>> criteria, params Expression<Func<T, object>>[] includes); Task<int> CountAsync(); Task<int> CountAsync(Expression<Func<T, bool>> criteria); T Add(T entity, bool IsCommit = false); void Update(T entity); void Delete(T entity, bool IsCommit = false); void DeleteWhere(Expression<Func<T, bool>> criteria, bool IsCommit = false); void AddRange(IEnumerable<T> entities, bool IsCommit = false); void DeleteRange(IEnumerable<T> entities, bool IsCommit = false); void Attach(T entity); void AttachRange(IEnumerable<T> entities); void Detach(T entity); void DetachRange(IEnumerable<T> entities); void AttachAsModified(T entity); bool Commit(); bool Commit(bool acceptAllChangesOnSuccess); Task<bool> CommitAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)); Task<bool> CommitAsync(CancellationToken cancellationToken = default(CancellationToken)); }
创建UserInfo实体类
[Table("UserInfo")] public class UserInfo : EntityBase { /// <summary> /// 用户名 /// </summary> public string UserName { get; set; } /// <summary> /// 用户密码 /// </summary> public string Password { get; set; } /// <summary> /// 用户邮箱 /// </summary> public string UserMail { get; set; } }
Infrastructure添加Nuget管理
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
Pomelo.EntityFrameworkCore.MySql
创建EntityBaseConfiguration
public abstract class EntityBaseConfiguration<T> : IEntityTypeConfiguration<T> where T : EntityBase { public virtual void Configure(EntityTypeBuilder<T> builder) { builder.HasKey(e => e.Id); ConfigureDerived(builder); } public abstract void ConfigureDerived(EntityTypeBuilder<T> b); }
创建UserInfoConfiguration
public class UserInfoConfiguration : EntityBaseConfiguration<UserInfo> { public override void ConfigureDerived(EntityTypeBuilder<UserInfo> b) { //根据自己情况看着瞎写吧 就这样 不BB } }
开整BaseContext
public class BaseContext : DbContext { public BaseContext(DbContextOptions<BaseContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //modelBuilder.ApplyConfiguration(new CustomerConfiguration()); modelBuilder.ApplyConfiguration(new UserInfoConfiguration()); } public DbSet<UserInfo> Users { get; set; } }
这时候的项目结构呢就变成了这个模样
好~到这里我打算结束了。算了。接着写吧。怕你们骂我。
开始创建数据库
修改webapi的startup.cs
ConfigureServices方法改为
public void ConfigureServices(IServiceCollection services) { var connection = Configuration.GetConnectionString("MySqlConnection"); services.AddDbContext<BaseContext>(options => options.UseMySql(connection)); services.AddSingleton<IConfiguration>(Configuration); services.AddMvc(); }
对喽,要修改appsettings.json
改成这样
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "MySqlConnection": "Data Source=localhost;Database=Test;User ID=root;Password=2323232323;pooling=true;CharSet=utf8;port=3306;sslmode=none" }, "RedisConfig": { "Redis_Default": { "Connection": "127.0.0.1: 6379", "InstanceName": "Redis1: " }, "Redis_6": { "Connection": "127.0.0.1: 6379", "DefaultDatabase": 6, "InstanceName": "Redis2: " }, "ReadWriteHosts": "172.16.75.230:6379" } }
然后我们开始创建数据库
Add-Migration MyFirstMigration
接着输入Update-Database执行。出现Done表示成功创建数据库。
本来写到这里我又不想写了。
但是写成这模样。不给大家看看实现方法 好像挺坑比的。
创建UserInfo的接口类:IUserInfoRepository
public interface IUserInfoRepository : IRepository<UserInfo> { /// <summary> /// 检查用户是存在 /// </summary> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <returns>存在返回用户实体,否则返回NULL</returns> UserInfo CheckUser(string userName, string password); }
创建UserInfo的实现类
public class UserInfoRepository : EfRepository<UserInfo>, IUserInfoRepository { public UserInfoRepository(BaseContext dbcontext) : base(dbcontext) { } /// <summary> /// 获取用户 /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public UserInfo CheckUser(string userName, string password) { return List(x => x.UserName == userName && x.Password == password).FirstOrDefault() ?? new UserInfo() { UserName = "哈哈哈哈" }; } }
去webapi整他丫的
在startup.cs中的ConfigureServices方法中撸入以下代码
var connection = Configuration.GetConnectionString("MySqlConnection"); services.AddDbContext<BaseContext>(options => options.UseMySql(connection)); services.AddScoped<IUserInfoRepository, UserInfoRepository>(); services.AddSingleton<IConfiguration>(Configuration);
好了。我们去创建一个UserApi
[Route("api/[controller]")] public class UserController : Controller { private IUserInfoRepository _userRepository; private IConfiguration _configuration; public UserController(IUserInfoRepository UserRepository, IConfiguration Configuration) { _userRepository = UserRepository; _configuration = Configuration; } [HttpPost("Get")] [EnableCors("any")] //设置跨域处理的 代理 public IActionResult Get() { var _Sel = _userRepository.CheckUser("", ""); return Ok(_Sel.UserName); } }
好了哥们们。完活了。