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;
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.