[英]How do I delete multiple records in database using EF Core?
我想根据里面的AdvertId
删除,而不是根据ID删除。 我找到了AdvertId
但我一直在删除。 我正在使用 CQRS 结构。 我的Repository
和IRepository
文件夹位于分开的位置。 在控制器部分,我通过查找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();
}
}
IR存储库:
Task<IEnumerable> DeleteAllAsync(T entity);
存储库;
public async Task<IEnumerable> DeleteAllAsync(T entity)
{
Context.Set<T>().Remove(entity);
Context.Entry(entity).State = EntityState.Deleted;
await Context.SaveChangesAsync();
return (IEnumerable)entity;
}
不幸的是,EF Core 不支持这些操作。 您必须全部获取它们然后删除。
var entities = _repository.GetAllByAdvertId(advertId);
_repository.Delete(entities);
和存储库实现
public async Task<IEnumerable> DeleteAllAsync(IEnumerable<T> entities)
{
foreach(var entity of entities){
Context.Set<T>().Remove(entity);
}
await Context.SaveChangesAsync();
return (IEnumerable)entity;
}
但是这个解决方案对于大数据集并不是最佳的。
如果你有一个大数据集,你可以使用Z.EntityFramework.Extensions.EFCore
包。
context.Customers
.Where(x => x.AdvertId == AdvertId)
.DeleteFromQuery();
这样,查询将在数据库中执行,您将不需要获取本地上下文中的所有数据来执行此操作。
查看示例批量操作方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.