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

15 篇文章 0 订阅

文章目录

方式一:

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;
		//不使用驼峰样式的key
		options.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
{       
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值