(仓储模式)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

相关文章

SQL BETWEEN 的常见用法小结

《SQLBETWEEN的常见用法小结》BETWEEN操作符是SQL中非常有用的工具,它允许你快速选取某个范围内的值,本文给大家介绍SQLBETWEEN的常见用法,感兴趣的朋友一起看看吧... 在SQL中,BETWEEN是一个操作符,用于选取介于两个值之间的数据。它包含这两个边界值。BETWEEN操作符常用

MySQL索引的优化之LIKE模糊查询功能实现

《MySQL索引的优化之LIKE模糊查询功能实现》:本文主要介绍MySQL索引的优化之LIKE模糊查询功能实现,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前缀匹配优化二、后缀匹配优化三、中间匹配优化四、覆盖索引优化五、减少查询范围六、避免通配符开头七、使用外部搜索引擎八、分

MySql match against工具详细用法

《MySqlmatchagainst工具详细用法》在MySQL中,MATCH……AGAINST是全文索引(Full-Textindex)的查询语法,它允许你对文本进行高效的全文搜素,支持自然语言搜... 目录一、全文索引的基本概念二、创建全文索引三、自然语言搜索四、布尔搜索五、相关性排序六、全文索引的限制七

数据库面试必备之MySQL中的乐观锁与悲观锁

《数据库面试必备之MySQL中的乐观锁与悲观锁》:本文主要介绍数据库面试必备之MySQL中乐观锁与悲观锁的相关资料,乐观锁适用于读多写少的场景,通过版本号检查避免冲突,而悲观锁适用于写多读少且对数... 目录一、引言二、乐观锁(一)原理(二)应用场景(三)示例代码三、悲观锁(一)原理(二)应用场景(三)示例

SQL表间关联查询实例详解

《SQL表间关联查询实例详解》本文主要讲解SQL语句中常用的表间关联查询方式,包括:左连接(leftjoin)、右连接(rightjoin)、全连接(fulljoin)、内连接(innerjoin)、... 目录简介样例准备左外连接右外连接全外连接内连接交叉连接自然连接简介本文主要讲解SQL语句中常用的表

SQL server配置管理器找不到如何打开它

《SQLserver配置管理器找不到如何打开它》最近遇到了SQLserver配置管理器打不开的问题,尝试在开始菜单栏搜SQLServerManager无果,于是将自己找到的方法总结分享给大家,对SQ... 目录方法一:桌面图标进入方法二:运行窗口进入方法三:查找文件路径方法四:检查 SQL Server 安

MySQL 中的 LIMIT 语句及基本用法

《MySQL中的LIMIT语句及基本用法》LIMIT语句用于限制查询返回的行数,常用于分页查询或取部分数据,提高查询效率,:本文主要介绍MySQL中的LIMIT语句,需要的朋友可以参考下... 目录mysql 中的 LIMIT 语句1. LIMIT 语法2. LIMIT 基本用法(1) 获取前 N 行数据(

MySQL 分区与分库分表策略应用小结

《MySQL分区与分库分表策略应用小结》在大数据量、复杂查询和高并发的应用场景下,单一数据库往往难以满足性能和扩展性的要求,本文将详细介绍这两种策略的基本概念、实现方法及优缺点,并通过实际案例展示如... 目录mysql 分区与分库分表策略1. 数据库水平拆分的背景2. MySQL 分区策略2.1 分区概念

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

MySQL 中查询 VARCHAR 类型 JSON 数据的问题记录

《MySQL中查询VARCHAR类型JSON数据的问题记录》在数据库设计中,有时我们会将JSON数据存储在VARCHAR或TEXT类型字段中,本文将详细介绍如何在MySQL中有效查询存储为V... 目录一、问题背景二、mysql jsON 函数2.1 常用 JSON 函数三、查询示例3.1 基本查询3.2