编辑 | blame | 历史 | 原始文档
using CMS.Plugin.$NameSpacePath$.Domain.$EntityName$;
using CMS.Plugin.$NameSpacePath$.EntityFrameworkCore.Extensions;
using CmsQueryExtensions.Extension;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using Volo.Abp;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;


namespace CMS.Plugin.$NameSpacePath$.EntityFrameworkCore.Repositories;

/// 
/// $ChinaComment$仓储实现
/// 
public class EfCore$EntityName$Repository : EfCoreRepository, I$EntityName$Repository
{
    /// 
    /// Initializes a new instance of the  class.
    /// 
    /// The database context provider.
    public EfCore$EntityName$Repository(IDbContextProvider dbContextProvider)
        : base(dbContextProvider)
    {
    }

    /// 
    /// 按照名称查找$ChinaComment$
    /// 
    /// 
    /// 
    /// 
    public virtual async Task<$EntityName$> FindByNameAsync(string name, CancellationToken cancellationToken = default)
    {
        return await (await GetDbSetAsync())
            .IncludeDetails()
            .Where(x => !x.IsDeleted)
            .OrderByDescending(x=>x.$OrderBy$) 
            .FirstOrDefaultAsync(t => t.$ValidateRepeatName$ == name, GetCancellationToken(cancellationToken));
    }

    /// 
    /// 验证名称是否存在$ChinaComment$
    /// 
    /// 校验值
    /// 
    /// 
    public async Task NameExistAsync(string name, Guid? id = null)
    {
        return await (await GetDbSetAsync()).WhereIf(id.HasValue, p => p.Id != id).Where(x => !x.IsDeleted).AnyAsync(x => x.$ValidateRepeatName$ == name);
    }

    /// 
    /// 获取最大排序$ChinaComment$
    /// 
    /// 
    public async Task GetMaxSortAsync()
    {
        var hasAny = await (await GetQueryableAsync())
            .Where(x => !x.IsDeleted).AnyAsync();
        if (!hasAny)
        {
            return 1;
        }

        var sort = await (await GetQueryableAsync())
            .Where(x => !x.IsDeleted).MaxAsync(x => x.Sort);
        return sort + 1;
    }

    /// 
    /// 获取分页列表$ChinaComment$
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public async Task> GetListAsync(FunReturnResultModel>> whereConditions, string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0, bool includeDetails = false, CancellationToken cancellationToken = default)
    {
        return await (await GetDbSetAsync())
            .IncludeDetails(includeDetails)
            .WhereIf(whereConditions != null, whereConditions.data)
            .Where(x => !x.IsDeleted)
            .OrderByDescending(x=>x.$OrderBy$)
            .PageBy(skipCount, maxResultCount)
            .ToListAsync(GetCancellationToken(cancellationToken));
    }

    /// 
    /// 获取总数$ChinaComment$
    /// 
    /// 
    /// 
    /// 
    public async Task GetCountAsync(FunReturnResultModel>> whereConditions, CancellationToken cancellationToken = default)
    {
        return await (await GetQueryableAsync())
            .WhereIf(whereConditions != null, whereConditions.data)
            .Where(x => !x.IsDeleted)
            .CountAsync(cancellationToken: GetCancellationToken(cancellationToken));
    }


    /// 
    public override async Task> WithDetailsAsync()
    {
        return (await GetQueryableAsync())
            .Where(x => !x.IsDeleted).IncludeDetails();
    }

    /// 
    /// 物理删除$ChinaComment$
    /// 
    /// 主键ID
    /// 
    /// 
    public virtual async Task DeletePermanentlyAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var entity = await (await GetDbSetAsync())
            .FirstOrDefaultAsync(x => x.Id == id && !x.IsDeleted, GetCancellationToken(cancellationToken));

        if (entity == null)
        {
            throw new Volo.Abp.Domain.Entities.EntityNotFoundException(typeof($EntityName$), id);
        }

        // 2. 获取 DbContext 并执行删除
        var dbContext = await GetDbContextAsync();

        // 直接执行 SQL 删除
        var sql = $"DELETE FROM $TableName$ WHERE Id ='{entity.Id.ToString()}'";
        await dbContext.Database.ExecuteSqlRawAsync(sql, cancellationToken);
    }

    /// 
    /// 批量物理删除$ChinaComment$(直接删除,不软删除)
    /// 
    /// 要删除的主键ID列表
    /// 
    /// 
    public virtual async Task BatchDeletePermanentlyAsync(IEnumerable ids, CancellationToken cancellationToken = default)
    {
        // 1. 查询符合条件的实体(未软删除的记录)
        var entities = await (await GetDbSetAsync())
            .Where(x => ids.Contains(x.Id) && !x.IsDeleted)
            .ToListAsync(GetCancellationToken(cancellationToken));

        if (!entities.Any())
        {
            // 如果没有需要删除的记录,直接返回(避免不必要的数据库操作)
            return;
        }

        // 2. 获取 DbContext 并执行批量删除
        var dbContext = await GetDbContextAsync();

        var idsToDelete = entities.Select(e => e.Id).ToList();

        // 直接执行 SQL 删除
        var sql = $"DELETE FROM $TableName$ WHERE Id IN ({string.Join(",", idsToDelete.Select(id => $"'{id}'"))})";
        await dbContext.Database.ExecuteSqlRawAsync(sql, cancellationToken);
    }

    /// 
    /// 根据条件获取$ChinaComment$列表
    /// 
    /// 
    /// 
    /// 
    public async Task> GetListByFilterAsync(Expression> whereConditions, CancellationToken cancellationToken = default)
    {
        return await (await GetDbSetAsync())
            .IncludeDetails()
            .WhereIf(whereConditions != null, whereConditions)
            .Where(x => !x.IsDeleted)
            .OrderByDescending(x => x.$OrderBy$)
            .ToListAsync(GetCancellationToken(cancellationToken));
    }

    /// 
    ///  根据条件获取单个$ChinaComment$
    /// 
    /// 
    /// 是否查询出多条就报错
    /// 
    /// 
    /// 
    public async Task<$EntityName$> GetSingleByFilterAsync(Expression> whereConditions, bool is​MultipleThrowException = false, CancellationToken cancellationToken = default)
    {
        if (is​MultipleThrowException)
        {
            var entitys = await (await GetDbSetAsync())
                .IncludeDetails()
                .WhereIf(whereConditions != null, whereConditions)
                .Where(x => !x.IsDeleted)
                .OrderByDescending(x => x.$OrderBy$)
                .ToListAsync(GetCancellationToken(cancellationToken));
            if (entitys?.Count > 1)
            {
                throw new UserFriendlyException("查询到多条记录");
            }
            return entitys?.FirstOrDefault();
        }
        else
        {
            return await (await GetDbSetAsync())
                .IncludeDetails()
                .WhereIf(whereConditions != null, whereConditions)
                .Where(x => !x.IsDeleted)
                .OrderByDescending(x => x.$OrderBy$)
                .FirstOrDefaultAsync(GetCancellationToken(cancellationToken));
        }
    }
}