zoukankan      html  css  js  c++  java
  • 在.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 = 0, 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的代码也可以自己去实现 

    参考文章

    作者:芝麻科技
    出处:芝麻麻雀-Asp.Net学习之路
    技术:C++,C#
    向我打赏
    加我微信,聊一聊技术
  • 相关阅读:
    fastText源码分析
    excel文件使用html导出
    oracle中对字符串进行分割,并反回随机段
    oracle锁表进行关闭
    .net中MVC Webapi多参数调用控制器方法
    C#线程调用带参数的方法,给控件赋值
    C#post调用接口并上传文件
    C#调用GPG命令进行加密解密文件操作
    C#中图片转换为Base64编码,Base64编码转换为图片
    GPG加密windows中使用
  • 原文地址:https://www.cnblogs.com/mzy-google/p/10734097.html
Copyright © 2011-2022 走看看