(仓储模式)ASP.NET Core用EF Core用的是Microsoft.EntityFrameworkCore.SqlServer 2.0.3版本

本文主要是介绍(仓储模式)ASP.NET Core用EF Core用的是Microsoft.EntityFrameworkCore.SqlServer 2.0.3版本,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 方式一:
    • 方式二

方式一:

using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System; 
using System.Linq; namespace MatrixWebApiCore.Common.Data
{public class DataContext : DbContext{public DataContext(DbContextOptions<DataContext> options): base(options){ }/// <summary>/// 报告实体,执行增删改查用/// </summary>public virtual DbSet<GroupCharts> GroupCharts { get; set; }public virtual DbSet<CombinationGroupCharts> CombinationGroupCharts { get; set; }/// <summary>/// 异常日志/// </summary>public virtual DbSet<Log> Log { get; set; }        }   
}
using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;namespace MatrixWebApiCore.Common.Data
{public class RepositoryBase<T> : IRepository<T> where T : BaseEntity, new(){private DataContext dbContext;private DbSet<T> dbSet;public RepositoryBase(DataContext _dbContext){dbContext = _dbContext;dbSet = dbContext.Set<T>();} public int Add(T entity){dbSet.Add(entity);return dbContext.SaveChanges();}public int Add(IEnumerable<T> entitys){foreach (var entity in entitys){dbSet.Add(entity);}return dbContext.SaveChanges();}public int Update(T entity){dbSet.Attach(entity);dbContext.Entry(entity).State = EntityState.Modified;return dbContext.SaveChanges();}public int Update(IEnumerable<T> entitys){foreach (var entity in entitys){dbSet.Attach(entity);dbContext.Entry(entity).State = EntityState.Modified;}return dbContext.SaveChanges();}public int Delete(T entity){dbSet.Attach(entity);dbSet.Remove(entity);return dbContext.SaveChanges();}public int Delete(Expression<Func<T, bool>> where){var entitys = this.GetList(where);foreach (var entity in entitys){dbSet.Remove(entity);}return dbContext.SaveChanges();}public T Get(Expression<Func<T, bool>> where){return dbSet.Where(where).FirstOrDefault();}public IQueryable<T> GetList(Expression<Func<T, bool>> where){return dbSet.Where(where);}public IQueryable<T> GetQuery(){return dbSet;}public IQueryable<T> GetQuery(Expression<Func<T, bool>> where){return dbSet.Where(where);}public IQueryable<T> GetAll(){return dbSet.AsParallel().AsQueryable();//return dbSet.AsQueryable();}public T GetAsNoTracking(Expression<Func<T, bool>> where){return dbSet.Where(where).AsNoTracking().FirstOrDefault();}public IQueryable<T> GetManyAsNoTracking(Expression<Func<T, bool>> where){return dbSet.AsNoTracking().Where(where);}public IQueryable<T> GetAllAsNoTracking(){return dbSet.AsNoTracking();}public bool Any(Expression<Func<T, bool>> @where){return dbSet.Any(where);}public int Count(Expression<Func<T, bool>> @where){return dbSet.Count(where);}}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;namespace MatrixWebApiCore.Common.Data
{public interface IRepository<T> where T : class{   int Add(T entity);int Add(IEnumerable<T> entitys);int Update(T entity);int Delete(T entity);       int Delete(Expression<Func<T, bool>> where);T Get(Expression<Func<T, bool>> where);IQueryable<T> GetList(Expression<Func<T, bool>> where);IQueryable<T> GetQuery(); IQueryable<T> GetQuery(Expression<Func<T, bool>> where);        IQueryable<T> GetAll();T GetAsNoTracking(Expression<Func<T, bool>> where);IQueryable<T> GetManyAsNoTracking(Expression<Func<T, bool>> where);       IQueryable<T> GetAllAsNoTracking();/// <summary>/// 检查是否存在/// </summary>/// <param name="where"></param>/// <returns></returns>bool Any(Expression<Func<T, bool>> where);int Count(Expression<Func<T, bool>> where);}
}
public interface IGroupChartsRepository :  IRepository<GroupCharts>
{ 
}public class GroupChartsRepository : RepositoryBase<GroupCharts>, IGroupChartsRepository
{public GroupChartsRepository(DataContext db) : base(db){ }
}[Produces("application/json")]
[Route("api/[controller]")]
public class ChartDataController : Controller
{private IGroupChartsRepository _group;public ChartDataController(IGroupChartsRepository group){_group = group;		 }[HttpPost("Delete")]public async Task<ActionResult> DeleteSavedReport([FromBody]BaseRequest parames){return await Task.Run(() =>{_group.Delete(w => w.Id == parames.Guid);}}}	

在Startup.cs注册服务


public void ConfigureServices(IServiceCollection services)
{string sqlConnection ="连接字符串";services.AddDbContext<DataContext>(option => option.UseSqlServer(sqlConnection));services.AddScoped<IGroupChartsRepository, GroupChartsRepository>();	//services.AddScoped<ILogRepository, LogRepository>(); //services.AddSingleton<CombinationWebClientData>();services.BuildServiceProvider();          //支持跨域services.AddCors();//注册内存缓存services.AddMemoryCache();//services.AddResponseCaching();services.AddMvcCore(options =>{//全局异常过滤器options.Filters.Add<ExceptionFilter>();//options.CacheProfiles.Add("test1", new CacheProfile());})//services.AddMvc().AddJsonFormatters()//配置返回json格式数据,不然会报错.AddApiExplorer()//全局配置Json序列化处理.AddJsonOptions(options =>{//忽略循环引用options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;//不使用驼峰样式的keyoptions.SerializerSettings.ContractResolver = new DefaultContractResolver();//设置时间格式options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";});
}

方式二

DataContext有区别,Repository有区别,然后是Startup.cs里面不用写这行代码:

services.AddDbContext<DataContext>(option => option.UseSqlServer(sqlConnection));

其他的写法和上面一模一样,这个注册服务要写:

services.AddScoped<IGroupChartsRepository, GroupChartsRepository>();
using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System; 
using System.Linq; namespace MatrixWebApiCore.Common.Data
{public class DataContext : DbContext{  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlServer("连接字符串");//optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");}/// <summary>/// 报告实体,执行增删改查用/// </summary>public virtual DbSet<GroupCharts> GroupCharts { get; set; }public virtual DbSet<CombinationGroupCharts> CombinationGroupCharts { get; set; }/// <summary>/// 异常日志/// </summary>public virtual DbSet<Log> Log { get; set; }        }   
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;namespace MatrixWebApiCore.Common.Data
{public interface IRepository<T> where T : class{DataContext GetDataContext { get; }int Add(T entity);int Add(IEnumerable<T> entitys);int Update(T entity);int Delete(T entity);       int Delete(Expression<Func<T, bool>> where);T Get(Expression<Func<T, bool>> where);IQueryable<T> GetList(Expression<Func<T, bool>> where);IQueryable<T> GetQuery(); IQueryable<T> GetQuery(Expression<Func<T, bool>> where);        IQueryable<T> GetAll();T GetAsNoTracking(Expression<Func<T, bool>> where);IQueryable<T> GetManyAsNoTracking(Expression<Func<T, bool>> where);       IQueryable<T> GetAllAsNoTracking();/// <summary>/// 检查是否存在/// </summary>/// <param name="where"></param>/// <returns></returns>bool Any(Expression<Func<T, bool>> where);int Count(Expression<Func<T, bool>> where);}
}
using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;namespace MatrixWebApiCore.Common.Data
{public class RepositoryBase<T> : IRepository<T> where T : BaseEntity, new(){ private DataContext dbContext;private DbSet<T> dbSet;public DataContext GetDataContext { get { return dbContext; } }public RepositoryBase(){dbContext = new DataContext();dbSet = dbContext.Set<T>();}public int Add(T entity){dbSet.Add(entity);return dbContext.SaveChanges();}public int Add(IEnumerable<T> entitys){foreach (var entity in entitys){dbSet.Add(entity);}return dbContext.SaveChanges();}public int Update(T entity){dbSet.Attach(entity);dbContext.Entry(entity).State = EntityState.Modified;return dbContext.SaveChanges();}public int Update(IEnumerable<T> entitys){foreach (var entity in entitys){dbSet.Attach(entity);dbContext.Entry(entity).State = EntityState.Modified;}return dbContext.SaveChanges();}public int Delete(T entity){dbSet.Attach(entity);dbSet.Remove(entity);return dbContext.SaveChanges();}public int Delete(Expression<Func<T, bool>> where){var entitys = this.GetList(where);foreach (var entity in entitys){dbSet.Remove(entity);}return dbContext.SaveChanges();}public T Get(Expression<Func<T, bool>> where){return dbSet.Where(where).FirstOrDefault();}public IQueryable<T> GetList(Expression<Func<T, bool>> where){return dbSet.Where(where);}public IQueryable<T> GetQuery(){return dbSet;}public IQueryable<T> GetQuery(Expression<Func<T, bool>> where){return dbSet.Where(where);}public IQueryable<T> GetAll(){return dbSet.AsParallel().AsQueryable();//return dbSet.AsQueryable();}public T GetAsNoTracking(Expression<Func<T, bool>> where){return dbSet.Where(where).AsNoTracking().FirstOrDefault();}public IQueryable<T> GetManyAsNoTracking(Expression<Func<T, bool>> where){return dbSet.AsNoTracking().Where(where);}public IQueryable<T> GetAllAsNoTracking(){return dbSet.AsNoTracking();}public bool Any(Expression<Func<T, bool>> @where){return dbSet.Any(where);}public int Count(Expression<Func<T, bool>> @where){return dbSet.Count(where);}}
}
public class GroupChartsRepository : RepositoryBase<GroupCharts>, IGroupChartsRepository
{       
}

这篇关于(仓储模式)ASP.NET Core用EF Core用的是Microsoft.EntityFrameworkCore.SqlServer 2.0.3版本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

MySQL分库分表的实践示例

《MySQL分库分表的实践示例》MySQL分库分表适用于数据量大或并发压力高的场景,核心技术包括水平/垂直分片和分库,需应对分布式事务、跨库查询等挑战,通过中间件和解决方案实现,最佳实践为合理策略、备... 目录一、分库分表的触发条件1.1 数据量阈值1.2 并发压力二、分库分表的核心技术模块2.1 水平分

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

Ubuntu如何升级Python版本

《Ubuntu如何升级Python版本》Ubuntu22.04Docker中,安装Python3.11后,使用update-alternatives设置为默认版本,最后用python3-V验证... 目China编程录问题描述前提环境解决方法总结问题描述Ubuntu22.04系统自带python3.10,想升级

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp