基于EF Core的Code First模式的DotNetCore快速开发框架
前言
最近接了几个小单子,因为是小单子,项目规模都比较小,业务相对来说,也比较简单。所以在选择架构的时候,考虑到效率方面的因素,就采取了asp.net+entity framework中的code first模式,从而可以进行快速开发。几个单子做完下来,顺便总结整理一下,近些时候也一直在学习dotnetcore,索性将项目都升级了,于是便有了这一套“基于EF Core的Code First模式的DotNetCore快速开发框架”。至于code first模式的优劣,此文将不再赘述。至于本文的目的,一是为了总结和整理工作这几年所学的一些知识,方便以后能够快速高效地接入项目中。再是分享出来,跟大家一起探讨学习,一起进步。欢迎各路大佬指正和建议^_^
项目地址
GitHub:
dotnetcore版本:https://github.com/VictorTzeng/Zxw.Framework.NetCore
.net framework版本:https://github.com/VictorTzeng/Zxw.Framework.Nfx
码云:
dotnetcore版本:https://gitee.com/ceo_bitch/Zxw.Framework.NetCore
.net framework版本:https://gitee.com/ceo_bitch/Zxw.Framework.Nfx
项目架构
此项目主要分成两部分:Zxw.Framework.NetCore (核心类库)和 NetCore.Sample (示例)两部分。如图所示:
Zxw.Framework.NetCore 项目说明:
- Attributes —— 一些常用的属性
- CodeGenerator —— 代码生成器,用于生成Repository和Service层的代码
- CodeTemplate —— Repository和Service层代码模板
- EfDbContext —— EF上下文
- Extensions —— 一些常用的扩展方法
- Filters —— 一些常用的拦截器
- Helpers —— 一些常用的帮助类
- IoC —— IoC容器封装类,Autofac
- IRepositories —— Repository接口类
- IServices —— Service接口类
- Middlewares —— 中间件
- Models —— 实体接口类,IBaseModel<TKey>
- Options —— 一些常用的配置类
- Repositories —— Repository层的父类
- Services —— Service层的父类
框架使用
如 NetCore.Sample 所示,按照此项目结构创建好:
- Zxw.Framework.Website —— 网站
- Zxw.Framework.Website.Controllers —— 控制器
- Zxw.Framework.Website.IRepositories —— 仓储接口
- Zxw.Framework.Website.IServices —— Service接口
- Zxw.Framework.Website.Models —— 实体
- Zxw.Framework.Website.Repositories —— 仓储
- Zxw.Framework.Website.Services —— Services
- Zxw.Framework.Website.ViewModels —— ViewModels
安装nuget package:
Install-Package Zxw.Framework.NetCore -Version 1.0.1
需要注意以下几点:
- 所有实体都需实现IBaseModel<TKey>接口(TKey是主键类型),如果需要在数据库中生成对应的数据表
- 如果IRepositories、IServices、Repositories、Services这四个项目没有单独建立,调用代码生成器生成的代码将存在于调用项目的目录下
- 利用代码生成器生成的代码文件需要手动添加到项目中
实体示例:
1 using System.ComponentModel.DataAnnotations; 2 using System.ComponentModel.DataAnnotations.Schema; 3 using Zxw.Framework.NetCore.Models; 4 5 namespace Zxw.Framework.Website.Models 6 { 7 public class TutorClassType:IBaseModel<int> 8 { 9 [Key] 10 [Column("TutorClassTypeId")] 11 public int Id { get; set; } 12 13 [Required] 14 [StringLength(maximumLength:50)] 15 public string TutorClassTypeName { get; set; } 16 public bool Active { get; set; } = true; 17 [StringLength(maximumLength:200)] 18 public string Remark { get; set; } 19 public int TutorClassCount { get; set; } 20 } 21 }
在Startup.cs文件中使用:
1 using System; 2 using System.Text; 3 using log4net; 4 using log4net.Repository; 5 using Microsoft.AspNetCore.Builder; 6 using Microsoft.AspNetCore.Hosting; 7 using Microsoft.Extensions.Caching.Distributed; 8 using Microsoft.Extensions.Caching.Memory; 9 using Microsoft.Extensions.Configuration; 10 using Microsoft.Extensions.DependencyInjection; 11 using Zxw.Framework.NetCore.EfDbContext; 12 using Zxw.Framework.NetCore.Filters; 13 using Zxw.Framework.NetCore.Helpers; 14 using Zxw.Framework.NetCore.IoC; 15 using Zxw.Framework.NetCore.Options; 16 17 namespace Zxw.Framework.Website 18 { 19 public class Startup 20 { 21 public static ILoggerRepository repository { get; set; } 22 public Startup(IConfiguration configuration) 23 { 24 Configuration = configuration; 25 //初始化log4net 26 repository = LogManager.CreateRepository("NETCoreRepository"); 27 Log4NetHelper.SetConfig(repository, "log4net.config"); 28 } 29 30 public IConfiguration Configuration { get; } 31 32 // This method gets called by the runtime. Use this method to add services to the container. 33 public IServiceProvider ConfigureServices(IServiceCollection services) 34 { 35 services.AddMvc(option=> 36 { 37 option.Filters.Add(new GlobalExceptionFilter()); 38 }); 39 services.AddMemoryCache();//启用MemoryCache 40 services.AddDistributedRedisCache(option => 41 { 42 option.Configuration = "localhost";//redis连接字符串 43 option.InstanceName = "";//Redis实例名称 44 });//启用Redis 45 services.Configure<MemoryCacheEntryOptions>( 46 options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)) //设置MemoryCache缓存有效时间为5分钟。 47 .Configure<DistributedCacheEntryOptions>(option => 48 option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));//设置Redis缓存有效时间为5分钟。 49 return InitIoC(services); 50 } 51 52 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 53 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 54 { 55 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); 56 if (env.IsDevelopment()) 57 { 58 app.UseDeveloperExceptionPage(); 59 app.UseBrowserLink(); 60 } 61 else 62 { 63 app.UseExceptionHandler("/Home/Error"); 64 } 65 66 app.UseStaticFiles(); 67 68 app.UseMvc(routes => 69 { 70 routes.MapRoute( 71 name: "default", 72 template: "{controller=Home}/{action=Index}/{id?}"); 73 }); 74 } 75 /// <summary> 76 /// IoC初始化 77 /// </summary> 78 /// <param name="services"></param> 79 /// <returns></returns> 80 private IServiceProvider InitIoC(IServiceCollection services) 81 { 82 var connectionString = Configuration.GetConnectionString("MsSqlServer"); 83 var dbContextOption = new DbContextOption 84 { 85 ConnectionString = connectionString, 86 ModelAssemblyName = "Zxw.Framework.Website.Models", 87 DbType = DbType.MSSQLSERVER 88 }; 89 var codeGenerateOption = new CodeGenerateOption 90 { 91 ModelsNamespace = "Zxw.Framework.Website.Models", 92 IRepositoriesNamespace = "Zxw.Framework.Website.IRepositories", 93 RepositoriesNamespace = "Zxw.Framework.Website.Repositories", 94 IServicsNamespace = "Zxw.Framework.Website.IServices", 95 ServicesNamespace = "Zxw.Framework.Website.Services" 96 }; 97 IoCContainer.Register(Configuration);//注册配置 98 IoCContainer.Register(dbContextOption);//注册数据库配置信息 99 IoCContainer.Register(codeGenerateOption);//注册代码生成器相关配置信息 100 IoCContainer.Register(typeof(DefaultDbContext));//注册EF上下文 101 IoCContainer.Register("Zxw.Framework.Website.Repositories", "Zxw.Framework.Website.IRepositories");//注册仓储 102 IoCContainer.Register("Zxw.Framework.Website.Services", "Zxw.Framework.Website.IServices");//注册service 103 return IoCContainer.Build(services); 104 } 105 } 106 }
使用代码生成器:
1 using System; 2 using System.Diagnostics; 3 using Microsoft.AspNetCore.Mvc; 4 using Zxw.Framework.NetCore.CodeGenerator; 5 using Zxw.Framework.NetCore.Helpers; 6 using Zxw.Framework.Website.IServices; 7 using Zxw.Framework.Website.ViewModels; 8 using Zxw.Framework.Website.Models; 9 10 namespace Zxw.Framework.Website.Controllers 11 { 12 public class HomeController : Controller 13 { 14 private ITutorClassTypeService iTutorClassTypeService; 15 16 public HomeController(ITutorClassTypeService tutorClassTypeService) 17 { 18 if(tutorClassTypeService==null) 19 throw new ArgumentNullException(nameof(tutorClassTypeService)); 20 iTutorClassTypeService = tutorClassTypeService; 21 } 22 public IActionResult Index() 23 { 24 CodeGenerator.Generate();//生成所有实体类对应的Repository和Service层代码文件 25 CodeGenerator.GenerateSingle<TutorClassType, int>();//生成单个实体类对应的Repository和Service层代码文件 26 27 return View(); 28 } 29 30 public IActionResult About() 31 { 32 ViewData["Message"] = "Your application description page."; 33 34 return View(); 35 } 36 37 public IActionResult Contact() 38 { 39 ViewData["Message"] = "Your contact page."; 40 41 return View(); 42 } 43 44 public IActionResult Error() 45 { 46 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 47 } 48 49 protected override void Dispose(bool disposing) 50 { 51 if (disposing) 52 { 53 iTutorClassTypeService.Dispose(); 54 } 55 base.Dispose(disposing); 56 } 57 } 58 }
总结
写博客真的很费力,希望自己能够坚持下去。
最后,欢迎各路大佬建议和拍砖~~