.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": ,
"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);
}
}
好了哥们们。完活了。
.net core webapi搭建(3)Code first+拆层三层+仓储的更多相关文章
- .Net Core WebAPI 搭建
.Net Core WebAPI 搭建 1.创建项目 使用开发工具为 Visual Studio 2017 2.创建 Controller 实体类 public class Book { public ...
- .net core webapi搭建(2)跨域
Core WebAPI中的跨域处理 在使用WebAPI项目的时候基本上都会用到跨域处理 Core WebAPI的项目中自带了跨域Cors的处理,不需要单独添加程序包 如图所示 修改 Configure ...
- NET CORE WebAPI 搭建--基础搭建
之前我们写了一个系统架构,是用.NET CORE 3.1.2 版本写的,没有使用前后端分离,说话老实话,本屌前端不是非常牛逼,太多的样式需要写,而且还要兼容响应式页面,一个人确实忙不过来,所以就想搞一 ...
- .net core webapi搭建(1)
创建一个webapi项目 修改launchSettings.json 将launchSettings.json中的IIS启动删掉.别问我为啥 原因就是IISEXPRESS有时候需要我手动重启.我嫌麻 ...
- SAAS云平台搭建札记: (三) AntDesign + .Net Core WebAPI权限控制、动态菜单的生成
我们知道,当下最火的前端框架,非蚂蚁金服的AntDesign莫属,这个框架不仅在国内非常有名,在国外GitHub上React前端框架也排名第一.而且这个框架涵盖了React.Vue.Angular等多 ...
- dotnet core webapi +vue 搭建前后端完全分离web架构
架构 服务端采用 dotnet core webapi 前端采用: Vue + router +elementUI+axios 问题 使用前后端完全分离的架构,首先遇到的问题肯定是跨域访问.前后端可 ...
- dotnet core webapi +vue 搭建前后端完全分离web架构(一)
架构 服务端采用 dotnet core webapi 前端采用: Vue + router +elementUI+axios 问题 使用前后端完全分离的架构,首先遇到的问题肯定是跨域访问.前后端可 ...
- net core Webapi基础工程搭建(六)——数据库操作_Part 2
目录 前言 开始 使用 小结 前言 昨天是写着写着发现,时间不早了,已经养成了晚上下班抽时间看看能写点儿啥的习惯(貌似),今天实在是不想让昨天没做完的事情影响,所以又坐下,沉下心(周末了),开始把数据 ...
- net core Webapi基础工程搭建(六)——数据库操作_Part 1
目录 前言 SqlSugar Service层 BaseService(基类) 小结 前言 后端开发最常打交道的就是数据库了(静态网站靠边),上一篇net core Webapi基础工程搭建(五)-- ...
随机推荐
- LeetCode111_求二叉树最小深度(二叉树问题)
题目: Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the s ...
- 第二阶段:2.商业需求分析及BRD:4.产品需求分析总结
产品的需求筛选 战略定位要考虑公司的战略问题.产品定位要分阶段,各个阶段的需求不同. 其实现在需求分析跟筛选都是非常快的. 不把需要当成需求,意思就是不要用户说需要什么就是什么,用户需要引导. 先分类 ...
- 0017 CSS 三大特性:层叠性、继承性、优先级
目标: 理解 能说出css样式冲突采取的原则 能说出那些常见的样式会有继承 应用 能写出CSS优先级的算法 能会计算常见选择器的叠加值 5.1 CSS层叠性 概念: 所谓层叠性是指多种CSS样式的叠加 ...
- 聊聊多线程那一些事儿 之 五 async.await深度剖析
hello task,咱们又见面啦!!是不是觉得很熟读的开场白,哈哈你哟这感觉那就对了,说明你已经阅读过了我总结的前面4篇关于task的文章,谢谢支持!感觉不熟悉的也没有关系,在文章末尾我会列出前四 ...
- iptables 添加80端口规则
iptables -t filter -A INPUT -p tcp -s 10.0.0.0/24 -j DROP 在filter表的input链做规则丢弃10.0.0.0网段的ip包iptables ...
- 选题Scrum立会报告+燃尽图 03
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2019fall/homework/8680 组长:杨天宇 组员:魏新,罗杨美慧,王歆瑶,徐丽君 组名:组长 第 ...
- FRPC 双向socket通讯 转发请求类轮子
一直在找一个能双向通讯的C#库 学识浅薄没有找到 于是封装一个预计BUG奇多的轮子 他是基于SuperSocket开发的 这样的 它跟传统的 架构不一样 它的最小架构 或者 客户端即是服务端 比如一个 ...
- vue-perview插件的使用方法
先给连接: https://github.com/LS1231/vue-preview 这是插件的文档 从文档中可以看出该插件已经值支持vue2.5以上了 安装: 引用 examples 注意: ...
- docker-网桥
使用桥接网络 在网络方面,桥接网络是链路层设备,它在网络段之间转发流量. 网桥可以是硬件设备或在主机内核中运行的软件设备. Docker而言,桥接网络使用软件桥接器,该软件桥接器允许连接到同一桥接网络 ...
- 鼠标右键新建Markdown文档
首先放一张github某项目中.md文件中的内容图片 Windows系统下,使用 Typora 软件来进入Markdown文档的编写非常容易,而且入门门槛非常的低 存在的问题: 习惯了使用Markdo ...