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

相关文章

如何开启和关闭3GB模式

https://jingyan.baidu.com/article/4d58d5414dfc2f9dd4e9c082.html

用Microsoft.Extensions.Hosting 管理WPF项目.

首先引入必要的包: <ItemGroup><PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" /><PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /><PackageReference Include="Serilog

mysql索引四(组合索引)

单列索引,即一个索引只包含单个列,一个表可以有多个单列索引,但这不是组合索引;组合索引,即一个索引包含多个列。 因为有事,下面内容全部转自:https://www.cnblogs.com/farmer-cabbage/p/5793589.html 为了形象地对比单列索引和组合索引,为表添加多个字段:    CREATE TABLE mytable( ID INT NOT NULL, use

mysql索引三(全文索引)

前面分别介绍了mysql索引一(普通索引)、mysql索引二(唯一索引)。 本文学习mysql全文索引。 全文索引(也称全文检索)是目前搜索引擎使用的一种关键技术。它能够利用【分词技术】等多种算法智能分析出文本文字中关键词的频率和重要性,然后按照一定的算法规则智能地筛选出我们想要的搜索结果。 在MySql中,创建全文索引相对比较简单。例如:我们有一个文章表(article),其中有主键ID(

mysql索引二(唯一索引)

前文中介绍了MySQL中普通索引用法,和没有索引的区别。mysql索引一(普通索引) 下面学习一下唯一索引。 创建唯一索引的目的不是为了提高访问速度,而只是为了避免数据出现重复。唯一索引可以有多个但索引列的值必须唯一,索引列的值允许有空值。如果能确定某个数据列将只包含彼此各不相同的值,在为这个数据列创建索引的时候就应该使用关键字UNIQUE,把它定义为一个唯一索引。 添加数据库唯一索引的几种

mysql索引一(普通索引)

mysql的索引分为两大类,聚簇索引、非聚簇索引。聚簇索引是按照数据存放的物理位置为顺序的,而非聚簇索引则不同。聚簇索引能够提高多行检索的速度、非聚簇索引则对单行检索的速度很快。         在这两大类的索引类型下,还可以降索引分为4个小类型:         1,普通索引:最基本的索引,没有任何限制,是我们经常使用到的索引。         2,唯一索引:与普通索引

ONLYOFFICE 8.1 版本桌面编辑器测评

在现代办公环境中,办公软件的重要性不言而喻。从文档处理到电子表格分析,再到演示文稿制作,强大且高效的办公软件工具能够极大提升工作效率。ONLYOFFICE 作为一个功能全面且开源的办公软件套件,一直以来都受到广大用户的关注与喜爱。而其最新发布的 ONLYOFFICE 8.1 版本桌面编辑器,更是带来了诸多改进和新特性。本文将详细评测 ONLYOFFICE 8.1 版本桌面编辑器,探讨其在功能、用户

17.用300行代码手写初体验Spring V1.0版本

1.1.课程目标 1、了解看源码最有效的方式,先猜测后验证,不要一开始就去调试代码。 2、浓缩就是精华,用 300行最简洁的代码 提炼Spring的基本设计思想。 3、掌握Spring框架的基本脉络。 1.2.内容定位 1、 具有1年以上的SpringMVC使用经验。 2、 希望深入了解Spring源码的人群,对 Spring有一个整体的宏观感受。 3、 全程手写实现SpringM

十四、观察者模式与访问者模式详解

21.观察者模式 21.1.课程目标 1、 掌握观察者模式和访问者模式的应用场景。 2、 掌握观察者模式在具体业务场景中的应用。 3、 了解访问者模式的双分派。 4、 观察者模式和访问者模式的优、缺点。 21.2.内容定位 1、 有 Swing开发经验的人群更容易理解观察者模式。 2、 访问者模式被称为最复杂的设计模式。 21.3.观察者模式 观 察 者 模 式 ( Obser