在.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 ...
随机推荐
- 一个jar包冲突引起的StackOverflowError
项目运行中错误信息:java.lang.IllegalStateException: Unable to complete the scan for annotations for web appli ...
- springboot整合redis-sentinel支持Cache注解
一.前提 已经存在一个redis-sentinel集群,两个哨兵分别如下: /home/redis-sentinel-cluster/sentinel-1.conf port 26379 dir &q ...
- go 闭包
看程序 package main import "fmt" func main() { f:=test2() fmt.Println(f()) fmt.Println(f()) } ...
- eclipse中补齐代码的快捷键
Shift+Alt+L比如我输入new TextView(this);按这个快捷键能自动生成TextView textView=new TextView(this); 例子: 代码将会变成如下:
- crontab计划不执行问题
问题现象:编写了一个自动释放磁盘空间的脚本,并将其加入到crontab中.crontab显示如下:# crontab -l10 5 * * * bash /home/backup/bin/clear. ...
- 初探ansible
Ansible 基于ssh的自动化运维工具 ansible 配置文件详解 ansible.cfg 文件 文件默认放置在/etc/ansible下,ansible读取配置文件的顺序是: 当前命令执行目录 ...
- centos7安装mariadb
~]# cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) 1.官方um安装mariadb 1).准备官方yum [mariadb ...
- _ZNote_Qt_重启软件
原文: http://wiki.qt.io/How_to_make_an_Application_restartable int main(int argc, char** argv) { QAppl ...
- flask-钩子函数&g对象
常用钩子函数 在Flask中钩子函数是使用特定的装饰器装饰的函数.钩子函数可以在正常执行的代码中,插入一段自己想要执行的代码.那么这种函数就叫做钩子函数.(hook) before_first_req ...
- AngularJS 关于ng-model和ng-bind还有{{}}
What's the difference between ng-model and ng-bind ng-bind has one-way data binding ($scope --> v ...