1

I want to delete according to the AdvertId in it, not according to the ID. I find AdvertId but I'm stuck on deletion. I am using CQRS structure. My Repository and IRepository folders are located separately. In the controller part, I am doing the transaction by finding the advertId.

public class Advert_CategoryPropertyDetailJunctionDeleteHandler : 
        IRequestHandler<Advert_CategoryPropertyDetailJunctionDelete, ApiResponse>
{
    private readonly IUnitOfWork _repo;

    public Advert_CategoryPropertyDetailJunctionDeleteHandler(IUnitOfWork repo)
    {
        _repo = repo;
    }

    public async Task<ApiResponse> Handle(Advert_CategoryPropertyDetailJunctionDelete 
    request, CancellationToken cancellationToken)
    {
        var mapped = await 
        _repo.AdvertCategoryPropertyDetailJunctions.GetAllAsync(request.predicate);

        if (mapped == null)
            return new ErrorApiResponse(ResultMessage.NotDeletedUser);

        await _repo.AdvertCategoryPropertyDetailJunctions.DeleteAllAsync((Advert_CategoryPropertyDetailJunction) mapped);

        return new SuccessApiResponse();
    }
}

IRrepository:

Task<IEnumerable> DeleteAllAsync(T entity);

Repository;

public async Task<IEnumerable> DeleteAllAsync(T entity)
{
    Context.Set<T>().Remove(entity);
    Context.Entry(entity).State = EntityState.Deleted;
    await Context.SaveChangesAsync();
    return (IEnumerable)entity;
}
1

2 Answers 2

9

This feature is introduced in EF7 described here.

It would look like:

await context.Customers
    .Where(x => x.AdvertId == advertIdToDelete)
    .ExecuteDeleteAsync();
Sign up to request clarification or add additional context in comments.

1 Comment

Is any additional package needed for this? I'm in .NET 7 and EF Core 7 and ExecuteDeleteAsync or ExecuteUpdateAsync are not available to me. Edit: forget it, working after adding Microsoft.EntityFrameworkCore.Relational package Thanks!
2

Unfortunately EF Core doesn't support these operations. You have to fetch them all and then delete.

var entities = _repository.GetAllByAdvertId(advertId);
_repository.Delete(entities);

and repository implementation

public async Task<IEnumerable> DeleteAllAsync(IEnumerable<T> entities)
    {
        foreach(var entity of entities){
            Context.Set<T>().Remove(entity);
        }
        await Context.SaveChangesAsync();
        return (IEnumerable)entity;

    }

but this solution is not optimal for large data sets.

If you have a large data set, you can use Z.EntityFramework.Extensions.EFCore package.

context.Customers
    .Where(x => x.AdvertId == AdvertId)
    .DeleteFromQuery();

In this way, the query will be executed in the database and you won't need to fetch all data in the local context to perform this operation.

See examples Batch Operations Methods

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.