首页 > 其他分享 >NET7下EFCORE的通用增删查改类

NET7下EFCORE的通用增删查改类

时间:2023-07-27 21:44:14浏览次数:37  
标签:predicate Task return TEntity entity 改类 EFCORE NET7 public

NET7下EFCORE的通用增删查改类 代码摘录自《深入浅出ASP.NET CORE》  

    /// <summary>
    /// 所有仓储的约定,此接口仅作为约定,用于标识他们
    /// </summary>
    /// <typeparam name="TEntity">传入仓储的实体模型</typeparam>
    /// <typeparam name="TPrimaryKey">传入仓储的主键类型</typeparam>
    public interface IRepository<TEntity,TPrimaryKey> where TEntity : class
    {
        #region 查询
        IQueryable<TEntity> GetAll();
        List<TEntity> GetAllList();
        Task<List<TEntity>> GetAllListAsync();
        List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate);
        Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate);
        TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate);
        Task<TEntity> FirstOrDefaultAsycn(Expression<Func<TEntity, bool>> predicate);
        #endregion

        #region 新增
        TEntity Insert(TEntity entity);
        Task<TEntity> InsertAsync(TEntity entity);
        #endregion

        #region 更新
        TEntity Update(TEntity entity);
        Task<TEntity> UpdateAsync(TEntity entity);
        #endregion

        #region 删除
        void Delete(TEntity entity);
        Task DeleteAsync(TEntity entity);
        void Delete(Expression<Func<TEntity, bool>> predicate);
        Task DeleteAsync(Expression<Func<TEntity, bool>> predicate);
        #endregion

        #region 总和计算
        int Count();
        Task<int> CountAsync();
        int Count(Expression<Func<TEntity, bool>> predicate);
        Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate);
        #endregion
    }

  

    /// <summary>
    /// 默认仓储的通用功能实现,用于所有的领域模型
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TPrimaryKey"></typeparam>
    public class RepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class
    {
        protected readonly AppDbContext _appDbContext;

        public RepositoryBase(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }

        public virtual DbSet<TEntity> Table=>_appDbContext.Set<TEntity>();

        public int Count()
        {
            return GetAll().Count();
        }

        public int Count(Expression<Func<TEntity, bool>> predicate)
        {
          return GetAll().Where(predicate).Count();
        }

        public async Task<int> CountAsync()
        {
           return await GetAll().CountAsync();
        }

        public async Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
        {
           return await GetAll().Where(predicate).CountAsync();
        }

        public void Delete(TEntity entity)
        {
            AttachIfNot(entity);
            Table.Remove(entity);
            Save();
        }

        public async Task DeleteAsync(TEntity entity)
        {
            AttachIfNot(entity);
            Table.Remove(entity);
            await SaveAsync();
        }

        public void Delete(Expression<Func<TEntity, bool>> predicate)
        {
            foreach (var entity in GetAll().Where(predicate).ToList())
            {
                Delete(entity);
            }
        }

        public async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate)
        {
            foreach (var entity in GetAll().Where(predicate).ToList())
            {
              await  DeleteAsync(entity);
            }
        }

        public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate)
        {
           return GetAll().FirstOrDefault(predicate);
        }

        public async Task<TEntity> FirstOrDefaultAsycn(Expression<Func<TEntity, bool>> predicate)
        {
           return await GetAll().FirstOrDefaultAsync(predicate);
        }

        public IQueryable<TEntity> GetAll()
        {
            return Table.AsQueryable();
        }

        public List<TEntity> GetAllList()
        {
           return GetAll().ToList();
        }

        public List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate)
        {
            return GetAll().Where(predicate).ToList();
        }

        public async Task<List<TEntity>> GetAllListAsync()
        {
           return await GetAll().ToListAsync();
        }

        public async Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate)
        {
           return await GetAll().Where(predicate).ToListAsync();
        }

        public TEntity Insert(TEntity entity)
        {
            var newEntity = Table.Add(entity).Entity;
            Save();
            return newEntity;
        }

        protected void Save()
        {
           _appDbContext.SaveChanges();
        }

        protected async Task SaveAsync() { 
            await _appDbContext.SaveChangesAsync();
        }
        /// <summary>
        /// 检查实体是否处于跟踪状态,如果是,则返回,如果不是,则添加跟踪状态
        /// </summary>
        /// <param name="entity"></param>
        protected virtual void AttachIfNot(TEntity entity) {
            var entry = _appDbContext.ChangeTracker.Entries().FirstOrDefault(e => e.Entity == entity);
            if (entry != null) { return; }
            Table.Attach(entity);
        }

        public async Task<TEntity> InsertAsync(TEntity entity)
        {
            var entityEntry = await Table.AddAsync(entity);
            await SaveAsync();
            return entityEntry.Entity;
        }

        public TEntity Update(TEntity entity)
        {
           AttachIfNot(entity);
            _appDbContext.Entry(entity).State = EntityState.Modified;
            Save();
            return entity;
        }

        public async Task<TEntity> UpdateAsync(TEntity entity)
        {
            AttachIfNot(entity);
            _appDbContext.Entry(entity).State = EntityState.Modified;
            await SaveAsync();
            return entity;
        }

   
    }

  

//假设有一学生接口需要有额外的登录接口,可新建一个IStudent接口,继承后只用加Login接口就行
    public interface IStudentRepository :IRepository<Student, int>
    {
        bool Login(string username, string password);
    }
    
//实现类除了要实现上面的接口,还要继承基类RepositoryBase
    public class StudentRepository : RepositoryBase<Student, int>, IStudentRepository
    {
        public StudentRepository(AppDbContext appDbContext) : base(appDbContext)
        {
        }

        public bool Login(string username, string password)
        {
            bool b = false;
            //GetAll是基类中的方法,返回 iquerable
            b = GetAll().Where(a=>a.username=username && a.password=password).Count()>0
            return b;    
        }
    }

  

//使用记得注入
  services.AddTransient(typeof(IRepository<,>), typeof(RepositoryBase<,>));
 services.AddTransient<IStudentRepository, StudentRepository>();

//控制器里的代码
private readonly IRepository<Student, int> _studentRepository;
private readonly IStudentRepository _studentRepository2;
 public WelcomeController(  IRepository<Student, int> studentRepository, IStudentRepository studentRepository2 )
        { 
            _studentRepository = studentRepository; 
            _studentRepository2 = studentRepository2;
        }
        public async Task<IActionResult> Index()
        {
 

            //_studentRepository2换成_studentRepository也成,只是没有Login方法
            Models.Student student =  await _studentRepository2.GetAll().FirstOrDefaultAsync();
            int count = await _studentRepository2.CountAsync();
            bool b = _studentRepository2.Login("niunan","123456");
            string str = $"取出一个学生:{student.Name},学生总数:{count}, 执行login方法结果:{false}";

            return Content($"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><div>原文:{src}</div><div>加密后:{jiami}</div><div>解密后:{jiemi}</div><div>{str}</div>","text/html");
        }

  

标签:predicate,Task,return,TEntity,entity,改类,EFCORE,NET7,public
From: https://www.cnblogs.com/niunan/p/17586173.html

相关文章

  • .Net7 IDE智能提示汉化
    本地化xml生成工具工具以dotnetcli发布,使用dotnettool进行安装dotnettoolinstall-gislocalizer复制.net7的汉化包已经有现成的了,可以直接进行安装islocalizerinstallauto-mnet7.0-lzh-cn复制工具会自动从github下载对应的包进行安装(可能需要访问加速......
  • Avalonia 使用EFCore调用SQLite实现Singleton全局注册
    Avalonia使用EFCore调用SQLite实现Singleton全局注册本篇博客是我的开源项目TerraMours.Chat.Ava的更新的记录分享,本次更新使用EntityFrameWorkCore调用SQLite,实现数据的本地化和查询的优化,删除了dbpross类(直接调用SQLite的操作类)。大大提高了代码的简洁度和易读性。通过全局......
  • NET7中sqlsugar的使用
    NET7中sqlsugar的使用仿《深入浅出ASP.NETCORE》这书里的IRepository和RepositoryBase usingSqlSugar;usingSystem.Linq.Expressions;namespaceWebApplication1.DAL{///<summary>///所有仓储的约定,此接口仅作为约定,用于标识他们///</summary>......
  • .NET7 for LoongArch64(国产龙芯)
    目前龙芯通过自己的指令集LA64支持了.Net7.0.1版本,一同被支持的有Ruby,Nodejs,Java,Electron,Python等。原文:在此处龙芯.Net7sdk下载地址:http://ftp.loongnix.cn/tmp/dotnet/7.0.5/7.0.5-ea1/dotnet-sdk-7.0.105-ea1-loongarch64.tar.xz在.Net8里面也可见支持LA64的代码,下面......
  • 第三十节:EFCore7.x版本新功能总结
    一.linq改进1.GroupBy(1).可以直接GroupBy进行toList()输出了. PS:从EFCore3.x--6.x不能直接groupby进行输出了。(2).这种类型的GroupBy不会直接转换为SQL,因此EFCore对返回的结果进行分组。但是,这不会导致从服务器传输任何其他数据。toList()才会查询。(3).案......
  • .NET7 中Autofac依赖注入整合多层,项目中可直接用
    一、配置Autofac替换内置DI1.安装Nuget包:Autofac.Extensions.DependencyInjection 2.Program.cs中加上builder.Host.UseServiceProviderFactory(newAutofacServiceProviderFactory());builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder=>{//在这里写......
  • .Net7发现System.Numerics.Vector矢量化的一个bug,Issues给了dotnet团队
    因为前几天做.Net7的矢量化性能优化,发现了一个bug。在类System.Numerics.Vector里面的成员变量IsHardwareAccelerated。但是实际上不确定这个bug是visualstudio2022的还是System.Numerics.Vector库的,个人认为应该是前者,也就是vs的bug。Vector.IsHardwareAccelerated返回的是Tr......
  • .NET7 中Autofac依赖注入整合多层,项目中可直接用
    目录一、配置Autofac替换内置DI二、构造函数注入三、属性注入四、批量注入五、手动获取实例六、其它用法1.不用接口,直接注入实例 2.一接口多实现 回到顶部一、配置Autofac替换内置DI1.安装Nuget包:Autofac.Extensions.DependencyInjection 2.Program.cs......
  • .NET7 中Autofac依赖注入整合多层,项目中可直接用
    一、配置Autofac替换内置DI1.安装Nuget包:Autofac.Extensions.DependencyInjection 2.Program.cs中加上builder.Host.UseServiceProviderFactory(newAutofacServiceProviderFactory());builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder=>{//在......
  • .Net7基础类型的优化和循环克隆优化
    前言.Net7里面对于基础类型的优化,是必不可少的。因为这些基础类型基本上都会经常用到,本篇除了基础类型的优化介绍之外,还有一个循环克隆的优化特性,也一并看下。概括1.基础类型优化基础类型的优化不会有些不会涉及ASM,主要是记忆。一:double.Parse和float.Parse,把某数值转换成d......