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

相关文章

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Java -jar命令如何运行外部依赖JAR包

《Java-jar命令如何运行外部依赖JAR包》在Java应用部署中,java-jar命令是启动可执行JAR包的标准方式,但当应用需要依赖外部JAR文件时,直接使用java-jar会面临类加载困... 目录引言:外部依赖JAR的必要性一、问题本质:类加载机制的限制1. Java -jar的默认行为2. 类加

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Maven 依赖发布与仓库治理的过程解析

《Maven依赖发布与仓库治理的过程解析》:本文主要介绍Maven依赖发布与仓库治理的过程解析,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下... 目录Maven 依赖发布与仓库治理引言第一章:distributionManagement配置的工程化实践1

Spring三级缓存解决循环依赖的解析过程

《Spring三级缓存解决循环依赖的解析过程》:本文主要介绍Spring三级缓存解决循环依赖的解析过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、循环依赖场景二、三级缓存定义三、解决流程(以ServiceA和ServiceB为例)四、关键机制详解五、设计约

gradle第三方Jar包依赖统一管理方式

《gradle第三方Jar包依赖统一管理方式》:本文主要介绍gradle第三方Jar包依赖统一管理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景实现1.顶层模块build.gradle添加依赖管理插件2.顶层模块build.gradle添加所有管理依赖包

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Maven如何手动安装依赖到本地仓库

《Maven如何手动安装依赖到本地仓库》:本文主要介绍Maven如何手动安装依赖到本地仓库问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、下载依赖二、安装 JAR 文件到本地仓库三、验证安装四、在项目中使用该依赖1、注意事项2、额外提示总结一、下载依赖登

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、