在.net core开发过程中,使用最多的就是注入方法。但是在.net core使用PetaPoco时,PetaPoco还不支持进行注入方式进行处理一些问题。

今天对PetaPoco进行了一些扩展,可以很方便的将PetaPoco进行注入操作,使用和EF很相似,但是更加简单

1、对PetaPoco.Compiled进行的一些扩展PetaPoco.Compiled.Extensions库

nuget:https://www.nuget.org/packages/PetaPoco.Compiled.Extensions/  欢迎使用

github:https://github.com/mzy666888/PetaPoco.Compiled.Extensions  欢迎star

具体扩展内容如下

1.1 创建PetaPocoDBContextOptions类

  1. namespace PetaPoco.Compiled.Extensions
  2. {
  3. using Microsoft.Extensions.Options;
  4.  
  5. public class PetaPocoDBContextOptions : IOptions<PetaPocoDBContextOptions>
  6. {
  7. /// <summary>The default configured TOptions instance</summary>
  8. PetaPocoDBContextOptions IOptions<PetaPocoDBContextOptions>.Value => this;
  9.  
  10. public string ConnectionString { get; set; }
  11. public string ProviderName { get; set; }
  12. }
  13.  
  14. }

1.2 创建接口IPetaPocoDBContext

接口继承IDatabase

  1. public interface IPetaPocoDBContext:IDatabase
  2. {
  3.  
  4. }

1.3 创建类PetaPocoDBContext

类继承IPetaPocoDBContext

  1. namespace PetaPoco.Compiled.Extensions
  2. {
  3. using Microsoft.Extensions.Options;
  4. using PetaPoco;
  5.  
  6. public abstract class PetaPocoDBContext:Database,IPetaPocoDBContext
  7. {
  8. /// <summary>
  9. /// 构造函数
  10. /// </summary>
  11. /// <param name="optionsAccessor"></param>
  12. protected PetaPocoDBContext(IOptions<PetaPocoDBContextOptions> optionsAccessor)
  13. : base(optionsAccessor.Value.ConnectionString, optionsAccessor.Value.ProviderName)
  14. {
  15.  
  16. }
  17. }
  18. }

1.4 添加对IServiceCollection的扩展

  1. namespace PetaPoco.Compiled.Extensions
  2. {
  3. using Microsoft.Extensions.DependencyInjection;
  4.  
  5. public static class PetaPocoDBContextServiceCollectionExtensions
  6. {
  7. public static IServiceCollection AddPetaPoco<T>(
  8. this IServiceCollection services,
  9. Action<PetaPocoDBContextOptions> setupAction)
  10. where T : class ,IPetaPocoDBContext
  11. {
  12. if (null == services)
  13. {
  14. throw new ArgumentNullException(nameof(services));
  15. }
  16.  
  17. if (null == setupAction)
  18. {
  19. throw new ArgumentNullException(nameof(setupAction));
  20. }
  21.  
  22. services.AddOptions();
  23. services.Configure(setupAction);
  24. services.AddScoped<IPetaPocoDBContext, T>();
  25. return services;
  26. }
  27. }
  28. }

这样对PetaPoco的扩展已经完成。

2.在ASP.NET Core MVC中使用PetaPoco.Compiled.Extensions

首先使用nuget对PetaPoco.Compiled.Extensions的引用

使用命令:Install-Package PetaPoco.Compiled.Extensions -Version 0.0.1

添加一个继承PetaPocoDBContext的DBContext类

  1. namespace PetaPoco.Compiled.Extensions.MvcTest.DBContexts
  2. {
  3. using Microsoft.Extensions.Options;
  4.  
  5. public class MvcPetaPocoDBContext:PetaPocoDBContext
  6. {
  7. /// <summary>
  8. /// 构造函数
  9. /// </summary>
  10. /// <param name="optionsAccessor"></param>
  11. public MvcPetaPocoDBContext(IOptions<PetaPocoDBContextOptions> optionsAccessor)
  12. : base(optionsAccessor)
  13. {
  14. }
  15. }
  16. }

添加好后,就可以在Startup中进行注入了,如下图所示

需要添加MySQL.Data的nuget引用

在appsettings.json文件中,数据库连接字符串配置如下:

  1. "ConnectionStrings": {
  2. "MySQL": {
  3. "MvcMySQL": "server=127.0.0.1;port=3306;uid=root;pwd=123456;database=WireCloud;",
  4. "provider": "MySql.Data.MySqlClient"
  5. }
  6. }

添加数据库表:Users(后续将使用EFCore进行CodeFirst进行处理)

添加对Users的操作接口和实现

  1. namespace PetaPoco.Compiled.Extensions.MvcTest.Services
  2. {
  3. using PetaPoco.Compiled.Extensions.MvcTest.Models;
  4.  
  5. public interface IUserService
  6. {
  7. IList<User> GetAll();
  8. }
  9.  
  10. public class UserService : IUserService
  11. {
  12. private PetaPocoDBContext _context;
  13.  
  14. public UserService(PetaPocoDBContext context)
  15. {
  16. _context = context;
  17. }
  18. public IList<User> GetAll()
  19. {
  20. return _context.Fetch<User>();
  21. }
  22. }
  23. }

在HomeController中添加一个Action

  1. namespace PetaPoco.Compiled.Extensions.MvcTest.Controllers
  2. {
  3. using PetaPoco.Compiled.Extensions.MvcTest.Services;
  4.  
  5. public class HomeController : Controller
  6. {
  7. private IUserService _userService;
  8.  
  9. public HomeController(IUserService userService)
  10. {
  11. _userService = userService;
  12. }
  13. public IActionResult Index()
  14. {
  15. return View();
  16. }
  17.  
  18. public IActionResult Privacy()
  19. {
  20. return View();
  21. }
  22.  
  23. [ResponseCache(Duration = , Location = ResponseCacheLocation.None, NoStore = true)]
  24. public IActionResult Error()
  25. {
  26. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  27. }
  28.  
  29. public IActionResult Users()
  30. {
  31. return View(_userService.GetAll());
  32. }
  33. }
  34. }

View实现

  1. @model System.Collections.Generic.IList<PetaPoco.Compiled.Extensions.MvcTest.Models.User>
  2.  
  3. <div>
  4. @foreach(var user in Model)
  5. {
  6. <div>@user.Uid</div>
  7. <div>@user.UserName</div>
  8. }
  9. </div>

运行并访问:http://localhost:52769/Home/Users

下一步实现EF Core 的CodeFirst功能,然后就能快速使用PetaPoco+EF Core相结合进行快速码代码了

EF  Core的代码也可以自己去实现

参考文章

在.net core 中PetaPoco结合EntityFrameworkCore使用codefirst方法进行开发的更多相关文章

  1. 在ASP.NET Core中构建路由的5种方法

    原文链接 :https://stormpath.com/blog/routing-in-asp-net-core 在ASP.NET Core中构建路由的5种方法 原文链接 :https://storm ...

  2. C#调用接口注意要点 socket,模拟服务器、客户端通信 在ASP.NET Core中构建路由的5种方法

    C#调用接口注意要点   在用C#调用接口的时候,遇到需要通过调用登录接口才能调用其他的接口,因为在其他的接口需要在登录的状态下保存Cookie值才能有权限调用, 所以首先需要通过调用登录接口来保存c ...

  3. ASP.Net Core中处理异常的几种方法

    本文将介绍在ASP.Net Core中处理异常的几种方法 1使用开发人员异常页面(The developer exception page) 2配置HTTP错误代码页 Configuring stat ...

  4. ASP.NET Core中app.UseDeveloperExceptionPage和app.UseExceptionHandler方法有什么用

    在新建一个ASP.NET Core项目后,在项目Startup类的Configure方法中默认会添加两个方法的调用,app.UseDeveloperExceptionPage和app.UseExcep ...

  5. .NET Core 中读取appsettings.json配置文件的方法

    appsettings.json配置文件结构如下: { "WeChatPay": { "WeChatApp_ID": "wx9999998999&qu ...

  6. 关于vue项目中axios跨域的解决方法(开发环境)

    1.在config文件中修改index.js proxyTable: { "/api":{ target: 'https://www.baidu.com/muc/',//你需要跨域 ...

  7. ASP.NET Core 中文文档 第三章 原理(6)全球化与本地化

    原文:Globalization and localization 作者:Rick Anderson.Damien Bowden.Bart Calixto.Nadeem Afana 翻译:谢炀(Kil ...

  8. Swift中字符串转化为Class的方法

    Swift中字符串转化为Class的方法 在开发中有时候会根据字符串进行对应类的转化,这样我们就可以动态根据服务器返回的字段,动态的加载类,比如优酷,微博等APP会在节假日等动态的TabBar.这样可 ...

  9. .Net Core 中使用PetaPoco ,T4生成模版

    话不多说,直接上源码. 1.引用NuGet 2.添加T4 <#@ template debug="true" hostspecific="false" l ...

随机推荐

  1. Oracle中将Clob字段转换成字符串

    1. 利用dbms_lob.substr()方法可将对应字段转换成字符串如下 select dbms_lob.substr(content) from NEWS 该方法有个缺点,当content字段长 ...

  2. 更新windows补丁时一直卡在搜索更新

    在微软下载好安装补丁Windows8.1-KB2999226-x64后,双击时一直停留在“正在此计算机上搜索”界面. 解决方案: 1.将windows 自动更新设置为:“从不检查更新”  . 2.关闭 ...

  3. C#运行时通过字符串实例化类对象

    备忘,记个C#版本. using System; using System.Collections.Generic; using System.Linq; using System.Text; usi ...

  4. vue el-upload form 同时提交

    项目需要form 表单和文件上传同时在一个请求,废话不多说上代码: 上传的组件使用pug格式 .row.my-4 .col-12 el-form(:model='domain', :rules='va ...

  5. Java 包与类的命名(util、service、tool、dao )区别

    util 通用的.与业务无关的,可以独立出来,可供其他项目使用.方法通常是public static,一般无类的属性,如果有,也是public static. service 与某一个业务有关,不是通 ...

  6. java集成memcached、redis防止缓存穿透

    下载相关jar,安装Memcached,安装教程:http://www.runoob.com/memcached/memcached-install.html spring配置memcached &l ...

  7. kvm-qcow2派生镜像的远程备份的方法!

    在虚拟化环境中,关于虚拟机的远程备份是一个比较重要的环节,这个是有关于整个机房挂掉之后,仍然可以恢复的最后一招. 在kvm中这种情况可以通过直接备份虚拟机的镜像文件(qcow2)到远端存储解决. 但有 ...

  8. jwt vs session 以rails 为例 (翻译部分)

    原文地址:https://pragmaticstudio.com/tutorials/rails-session-cookies-for-api-authentication 普通方式: 令牌为基础的 ...

  9. Gitee(码云)、Github同时配置ssh key

    一.cd ~/.ssh 二.通过下面的命令,依次生成两个平台的key $ ssh-keygen -t rsa -C "xxxxxxx@qq.com" -f "github ...

  10. 闵可夫斯基和(Mincowsky sum)

    一.概述 官方定义:两个图形A,B的闵可夫斯基和C={a+b|a∈A,b∈B}通俗一点:从原点向图形A内部的每一个点做向量,将图形B沿每个向量移动,所有的最终位置的并便是闵可夫斯基和(具有交换律) 例 ...