本文主要是介绍(仓储模式)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版本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!