在.net core 中PetaPoco结合EntityFrameworkCore使用codefirst方法进行开发
在.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类
- namespace PetaPoco.Compiled.Extensions
- {
- using Microsoft.Extensions.Options;
- public class PetaPocoDBContextOptions : IOptions<PetaPocoDBContextOptions>
- {
- /// <summary>The default configured TOptions instance</summary>
- PetaPocoDBContextOptions IOptions<PetaPocoDBContextOptions>.Value => this;
- public string ConnectionString { get; set; }
- public string ProviderName { get; set; }
- }
- }
1.2 创建接口IPetaPocoDBContext
接口继承IDatabase
- public interface IPetaPocoDBContext:IDatabase
- {
- }
1.3 创建类PetaPocoDBContext
类继承IPetaPocoDBContext
- namespace PetaPoco.Compiled.Extensions
- {
- using Microsoft.Extensions.Options;
- using PetaPoco;
- public abstract class PetaPocoDBContext:Database,IPetaPocoDBContext
- {
- /// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="optionsAccessor"></param>
- protected PetaPocoDBContext(IOptions<PetaPocoDBContextOptions> optionsAccessor)
- : base(optionsAccessor.Value.ConnectionString, optionsAccessor.Value.ProviderName)
- {
- }
- }
- }
1.4 添加对IServiceCollection的扩展
- namespace PetaPoco.Compiled.Extensions
- {
- using Microsoft.Extensions.DependencyInjection;
- public static class PetaPocoDBContextServiceCollectionExtensions
- {
- public static IServiceCollection AddPetaPoco<T>(
- this IServiceCollection services,
- Action<PetaPocoDBContextOptions> setupAction)
- where T : class ,IPetaPocoDBContext
- {
- if (null == services)
- {
- throw new ArgumentNullException(nameof(services));
- }
- if (null == setupAction)
- {
- throw new ArgumentNullException(nameof(setupAction));
- }
- services.AddOptions();
- services.Configure(setupAction);
- services.AddScoped<IPetaPocoDBContext, T>();
- return services;
- }
- }
- }
这样对PetaPoco的扩展已经完成。
2.在ASP.NET Core MVC中使用PetaPoco.Compiled.Extensions
首先使用nuget对PetaPoco.Compiled.Extensions的引用
使用命令:Install-Package PetaPoco.Compiled.Extensions -Version 0.0.1
添加一个继承PetaPocoDBContext的DBContext类
- namespace PetaPoco.Compiled.Extensions.MvcTest.DBContexts
- {
- using Microsoft.Extensions.Options;
- public class MvcPetaPocoDBContext:PetaPocoDBContext
- {
- /// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="optionsAccessor"></param>
- public MvcPetaPocoDBContext(IOptions<PetaPocoDBContextOptions> optionsAccessor)
- : base(optionsAccessor)
- {
- }
- }
- }
添加好后,就可以在Startup中进行注入了,如下图所示
需要添加MySQL.Data的nuget引用
在appsettings.json文件中,数据库连接字符串配置如下:
- "ConnectionStrings": {
- "MySQL": {
- "MvcMySQL": "server=127.0.0.1;port=3306;uid=root;pwd=123456;database=WireCloud;",
- "provider": "MySql.Data.MySqlClient"
- }
- }
添加数据库表:Users(后续将使用EFCore进行CodeFirst进行处理)
添加对Users的操作接口和实现
- namespace PetaPoco.Compiled.Extensions.MvcTest.Services
- {
- using PetaPoco.Compiled.Extensions.MvcTest.Models;
- public interface IUserService
- {
- IList<User> GetAll();
- }
- public class UserService : IUserService
- {
- private PetaPocoDBContext _context;
- public UserService(PetaPocoDBContext context)
- {
- _context = context;
- }
- public IList<User> GetAll()
- {
- return _context.Fetch<User>();
- }
- }
- }
在HomeController中添加一个Action
- namespace PetaPoco.Compiled.Extensions.MvcTest.Controllers
- {
- using PetaPoco.Compiled.Extensions.MvcTest.Services;
- public class HomeController : Controller
- {
- private IUserService _userService;
- public HomeController(IUserService userService)
- {
- _userService = userService;
- }
- public IActionResult Index()
- {
- return View();
- }
- public IActionResult Privacy()
- {
- return View();
- }
- [ResponseCache(Duration = , Location = ResponseCacheLocation.None, NoStore = true)]
- public IActionResult Error()
- {
- return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
- public IActionResult Users()
- {
- return View(_userService.GetAll());
- }
- }
- }
View实现
- @model System.Collections.Generic.IList<PetaPoco.Compiled.Extensions.MvcTest.Models.User>
- <div>
- @foreach(var user in Model)
- {
- <div>@user.Uid</div>
- <div>@user.UserName</div>
- }
- </div>
运行并访问:http://localhost:52769/Home/Users
下一步实现EF Core 的CodeFirst功能,然后就能快速使用PetaPoco+EF Core相结合进行快速码代码了
EF Core的代码也可以自己去实现
在.net core 中PetaPoco结合EntityFrameworkCore使用codefirst方法进行开发的更多相关文章
- 在ASP.NET Core中构建路由的5种方法
原文链接 :https://stormpath.com/blog/routing-in-asp-net-core 在ASP.NET Core中构建路由的5种方法 原文链接 :https://storm ...
- C#调用接口注意要点 socket,模拟服务器、客户端通信 在ASP.NET Core中构建路由的5种方法
C#调用接口注意要点 在用C#调用接口的时候,遇到需要通过调用登录接口才能调用其他的接口,因为在其他的接口需要在登录的状态下保存Cookie值才能有权限调用, 所以首先需要通过调用登录接口来保存c ...
- ASP.Net Core中处理异常的几种方法
本文将介绍在ASP.Net Core中处理异常的几种方法 1使用开发人员异常页面(The developer exception page) 2配置HTTP错误代码页 Configuring stat ...
- ASP.NET Core中app.UseDeveloperExceptionPage和app.UseExceptionHandler方法有什么用
在新建一个ASP.NET Core项目后,在项目Startup类的Configure方法中默认会添加两个方法的调用,app.UseDeveloperExceptionPage和app.UseExcep ...
- .NET Core 中读取appsettings.json配置文件的方法
appsettings.json配置文件结构如下: { "WeChatPay": { "WeChatApp_ID": "wx9999998999&qu ...
- 关于vue项目中axios跨域的解决方法(开发环境)
1.在config文件中修改index.js proxyTable: { "/api":{ target: 'https://www.baidu.com/muc/',//你需要跨域 ...
- ASP.NET Core 中文文档 第三章 原理(6)全球化与本地化
原文:Globalization and localization 作者:Rick Anderson.Damien Bowden.Bart Calixto.Nadeem Afana 翻译:谢炀(Kil ...
- Swift中字符串转化为Class的方法
Swift中字符串转化为Class的方法 在开发中有时候会根据字符串进行对应类的转化,这样我们就可以动态根据服务器返回的字段,动态的加载类,比如优酷,微博等APP会在节假日等动态的TabBar.这样可 ...
- .Net Core 中使用PetaPoco ,T4生成模版
话不多说,直接上源码. 1.引用NuGet 2.添加T4 <#@ template debug="true" hostspecific="false" l ...
随机推荐
- Oracle中将Clob字段转换成字符串
1. 利用dbms_lob.substr()方法可将对应字段转换成字符串如下 select dbms_lob.substr(content) from NEWS 该方法有个缺点,当content字段长 ...
- 更新windows补丁时一直卡在搜索更新
在微软下载好安装补丁Windows8.1-KB2999226-x64后,双击时一直停留在“正在此计算机上搜索”界面. 解决方案: 1.将windows 自动更新设置为:“从不检查更新” . 2.关闭 ...
- C#运行时通过字符串实例化类对象
备忘,记个C#版本. using System; using System.Collections.Generic; using System.Linq; using System.Text; usi ...
- vue el-upload form 同时提交
项目需要form 表单和文件上传同时在一个请求,废话不多说上代码: 上传的组件使用pug格式 .row.my-4 .col-12 el-form(:model='domain', :rules='va ...
- Java 包与类的命名(util、service、tool、dao )区别
util 通用的.与业务无关的,可以独立出来,可供其他项目使用.方法通常是public static,一般无类的属性,如果有,也是public static. service 与某一个业务有关,不是通 ...
- java集成memcached、redis防止缓存穿透
下载相关jar,安装Memcached,安装教程:http://www.runoob.com/memcached/memcached-install.html spring配置memcached &l ...
- kvm-qcow2派生镜像的远程备份的方法!
在虚拟化环境中,关于虚拟机的远程备份是一个比较重要的环节,这个是有关于整个机房挂掉之后,仍然可以恢复的最后一招. 在kvm中这种情况可以通过直接备份虚拟机的镜像文件(qcow2)到远端存储解决. 但有 ...
- jwt vs session 以rails 为例 (翻译部分)
原文地址:https://pragmaticstudio.com/tutorials/rails-session-cookies-for-api-authentication 普通方式: 令牌为基础的 ...
- Gitee(码云)、Github同时配置ssh key
一.cd ~/.ssh 二.通过下面的命令,依次生成两个平台的key $ ssh-keygen -t rsa -C "xxxxxxx@qq.com" -f "github ...
- 闵可夫斯基和(Mincowsky sum)
一.概述 官方定义:两个图形A,B的闵可夫斯基和C={a+b|a∈A,b∈B}通俗一点:从原点向图形A内部的每一个点做向量,将图形B沿每个向量移动,所有的最终位置的并便是闵可夫斯基和(具有交换律) 例 ...