EFcore Repository 依赖注入

2023-10-21 23:08

本文主要是介绍EFcore Repository 依赖注入,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于EFcore 实现基本的数据库操作

0.代码关系与结构如图所示:

存在两个数据表,分别是UserInfo表、Contacts表,应用Scaffold-DbContext生成Model

创建两个文件夹,分别是Services(接口)、Implementation(接口的实现)
在这里插入图片描述
在这里插入图片描述

1.操作步骤:

a.创建IRepository接口;
b.创建RepositoryBase:IRepository 实现基本数据库操作
c.分别创建IUserInfoRepository、IContactRepository
d.分别创建UserInfoRepository、ContactRepository
e.创建IRepositoryWrapper
f.创建RepositoryWrapper : IRepositoryWrapper 用于实现依赖注入
g.依赖注入
h.构造函数注入与应用

2.创建IRepository接口:

using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;namespace WebApplication24.Services
{public interface IRepository<T>{Task<bool> Insert(T t);Task<bool> Update(T t);Task<bool> Delete(T t);Task<IEnumerable<T>> GetAllAsync();      Task<IEnumerable<T>> GetByConditionAsync(Expression<Func<T, bool>> expression);Task<T> GetByIdAsync(object id);Task<bool> IsExistAsync(object id);Task<int> GetCountAsync(T t);Task<IDbContextTransaction> BeginTransactionAsync(IsolationLevel isolationLevel = IsolationLevel.Unspecified,CancellationToken cancellationToken = default);}
}

3.创建RepositoryBase:IRepository 实现基本数据库操作

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;namespace WebApplication24.Services
{public class RepositoryBase<T> : IRepository<T> where T : class{private readonly DbContext dbContext;public RepositoryBase(DbContext dbContext) => this.dbContext = dbContext;public async Task<bool> Insert(T entity){bool bRet = false;if (entity == null){return bRet;}bRet = IsEntityValid(entity);if (!bRet){return bRet;}dbContext.Set<T>().Add(entity);return await dbContext.SaveChangesAsync() > 0;}public async Task<bool> Update(T entity){bool bRet = false;if (entity == null){return bRet;}bRet = IsEntityTracked(entity);if (!bRet){return bRet;}bRet = IsEntityValid(entity);if (!bRet){return bRet;}dbContext.Set<T>().Update(entity);return await dbContext.SaveChangesAsync() > 0;}public async Task<bool> Delete(T entity){bool bRet = false;if (entity == null){return bRet;}bRet = IsEntityTracked(entity);if (!bRet){return bRet;}bRet = IsEntityValid(entity);if (!bRet){return bRet;}dbContext.Set<T>().Remove(entity);return await dbContext.SaveChangesAsync() > 0;}public Task<IEnumerable<T>> GetAllAsync(){return Task.FromResult(dbContext.Set<T>().AsEnumerable());}public Task<IEnumerable<T>> GetByConditionAsync(Expression<Func<T, bool>> expression){return Task.FromResult(dbContext.Set<T>().Where(expression).AsEnumerable());}public async Task<T> GetByIdAsync(object id){if (id == null){return null;}return await dbContext.Set<T>().FindAsync(id);}public async Task<bool> IsExistAsync(object id){if (id == null){return false;}return await dbContext.Set<T>().FindAsync(id) != null;}public async Task<int> GetCountAsync(T entity){return await dbContext.Set<T>().CountAsync();}public async Task<IDbContextTransaction> BeginTransactionAsync(IsolationLevel isolationLevel = System.Data.IsolationLevel.Unspecified, CancellationToken cancellationToken = default){return await dbContext.Database.BeginTransactionAsync(isolationLevel, cancellationToken);}private bool IsEntityValid(T entity){//判断entity是否是DbContext的ModelIEntityType entityType = dbContext.Model.FindEntityType(typeof(T));if (entityType == null){return false;}//获取主键值名称string keyName = entityType.FindPrimaryKey().Properties.Select(p => p.Name).FirstOrDefault();if (string.IsNullOrEmpty(keyName)){return false;}//获取主键类型Type keyType = entityType.FindPrimaryKey().Properties.Select(p => p.ClrType).FirstOrDefault();if (keyType == null){return false;}//获取主键值类型的默认值object keyDefaultValue = keyType.IsValueType ? Activator.CreateInstance(keyType) : null;//获取当前主键值object keyValue = entity.GetType().GetProperty(keyName).GetValue(entity, null);if (keyDefaultValue.Equals(keyValue)){return false;}           else{return true;}}private bool IsEntityTracked(T entity){EntityEntry<T> trackedEntity = dbContext.ChangeTracker.Entries<T>().FirstOrDefault(o => o.Entity == entity);if (trackedEntity == null){return false;}else{return true;}}}     
}

4.创建IUserInfoRepository、IContactRepository

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication24.Models;namespace WebApplication24.Services
{public interface IUserInfoRepository : IRepository<UserInfo>{}public interface IContactRepository : IRepository<Contact>{}
}

5.创建UserInfoRepository、ContactRepository

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication24.Models;namespace WebApplication24.Services
{public class UserInfoRepository : RepositoryBase<UserInfo>,IUserInfoRepository{public UserInfoRepository(DbContext dbContext):base(dbContext){}}public class ContactRepository : RepositoryBase<Contact>,IContactRepository{public ContactRepository(DbContext dbContext):base(dbContext){}}
}

6.创建IRepositoryWrapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace WebApplication24.Services
{public interface IRepositoryWrapper{IUserInfoRepository UserInfo{ get; }IContactRepository Contact { get; }}
}

7.创建RepositoryWrapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication24.Models;namespace WebApplication24.Services
{public class RepositoryWrapper : IRepositoryWrapper{private readonly ExampleContext _exampleContext;public RepositoryWrapper(ExampleContext exampleContext) => _exampleContext = exampleContext;public IUserInfoRepository UserInfo => new UserInfoRepository(_exampleContext);public IContactRepository Contact => new ContactRepository(_exampleContext);}
}

8.依赖注入 StartUp类

public void ConfigureServices(IServiceCollection services)
{services.AddControllersWithViews();services.AddDbContext<ExampleContext>(options => {options.UseSqlServer(Configuration.GetConnectionString("defaultConnection"));});services.AddScoped<IRepositoryWrapper, RepositoryWrapper>();
}

9.构造注入

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WebApplication24.Models;
using WebApplication24.Services;namespace WebApplication24.Controllers
{public class HomeController : Controller{private readonly ILogger<HomeController> _logger;private readonly IRepositoryWrapper _db;public HomeController(ILogger<HomeController> logger,IRepositoryWrapper repositoryWrapper){_logger = logger;_db = repositoryWrapper;}public async Task<IActionResult> Index(){IDbContextTransaction transaction = await _db.UserInfo.BeginTransactionAsync(IsolationLevel.ReadCommitted);try{                await _db.UserInfo.Delete(new UserInfo() { Id = 4, Name = "Hanmeimei", Age = 30 });await _db.Contact.Insert(new Contact() { Id = 40, Name = "Hanmeimei", Phone = "13155556666", Address = "Beijing" });await transaction.CommitAsync();}catch (Exception){await transaction.RollbackAsync();}return View();           }        }
}

自学EFCore,具体源码在我的Space里可以下载,共勉喽
Happy Ending

这篇关于EFcore Repository 依赖注入的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/257520

相关文章

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Python依赖库的几种离线安装方法总结

《Python依赖库的几种离线安装方法总结》:本文主要介绍如何在Python中使用pip工具进行依赖库的安装和管理,包括如何导出和导入依赖包列表、如何下载和安装单个或多个库包及其依赖,以及如何指定... 目录前言一、如何copy一个python环境二、如何下载一个包及其依赖并安装三、如何导出requirem

Python如何快速下载依赖

《Python如何快速下载依赖》本文介绍了四种在Python中快速下载依赖的方法,包括使用国内镜像源、开启pip并发下载功能、使用pipreqs批量下载项目依赖以及使用conda管理依赖,通过这些方法... 目录python快速下载依赖1. 使用国内镜像源临时使用镜像源永久配置镜像源2. 使用 pip 的并

SpringBoot项目注入 traceId 追踪整个请求的日志链路(过程详解)

《SpringBoot项目注入traceId追踪整个请求的日志链路(过程详解)》本文介绍了如何在单体SpringBoot项目中通过手动实现过滤器或拦截器来注入traceId,以追踪整个请求的日志链... SpringBoot项目注入 traceId 来追踪整个请求的日志链路,有了 traceId, 我们在排

python安装whl包并解决依赖关系的实现

《python安装whl包并解决依赖关系的实现》本文主要介绍了python安装whl包并解决依赖关系的实现,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录一、什么是whl文件?二、我们为什么需要使用whl文件来安装python库?三、我们应该去哪儿下

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

使用maven依赖详解

《使用maven依赖详解》本文主要介绍了Maven的基础知识,包括Maven的简介、仓库类型、常用命令、场景举例、指令总结、依赖范围、settings.xml说明等,同时,还详细讲解了Maven依赖的... 目录1. maven基础1.1 简介1.2 仓库类型1.3 常用命令1.4 场景举例1.5 指令总结

SQL注入漏洞扫描之sqlmap详解

《SQL注入漏洞扫描之sqlmap详解》SQLMap是一款自动执行SQL注入的审计工具,支持多种SQL注入技术,包括布尔型盲注、时间型盲注、报错型注入、联合查询注入和堆叠查询注入... 目录what支持类型how---less-1为例1.检测网站是否存在sql注入漏洞的注入点2.列举可用数据库3.列举数据库

Spring核心思想之浅谈IoC容器与依赖倒置(DI)

《Spring核心思想之浅谈IoC容器与依赖倒置(DI)》文章介绍了Spring的IoC和DI机制,以及MyBatis的动态代理,通过注解和反射,Spring能够自动管理对象的创建和依赖注入,而MyB... 目录一、控制反转 IoC二、依赖倒置 DI1. 详细概念2. Spring 中 DI 的实现原理三、

python中poetry安装依赖

《python中poetry安装依赖》本文主要介绍了Poetry工具及其在Python项目中的安装和使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前言1. 为什么pip install poetry 会造成依赖冲突1.1 全局环境依赖混淆:1