I am here to ask question about:
- is it good practice to insert many records using CQRS and MediatR?
- how to structure that in terms of names and folders?
A have to insert into database over 500 records and now I am doing it like this:
foreach (var item in list)
{
var command = new CreateItemCommand()
{
Name = "Adam",
Job = "Support"
}
await _mediator.Send(command);
}
This is obviously an example, my object's are much bigger. The problem is that, it takes around 15 seconds to insert 500 records..
If I could do something like this:
var list = new List<Person>();
foreach (var item in persons)
{
list.Add(new Person()
{
Name = "Adam",
Job = "Support"
});
}
var command = new CreateManyItemsCommand()
{
List = list
}
await _mediator.Send(command);
The same operation will be much faster.
So, let me back to questions:
is it good practise?
Structure: db/Commands/CreateManyItems/CreateManyItemsCommand.cs or db/Commands/CreateItem/CreateManyItemsCommand.cs ?
Please, share some thoughts on this :)
If anyone wondering how my current handler looks, here it is:
public class CreateItemCommand : IRequest<int>, IMapFrom<Item>
{
public string Name { get; set; }
public string Job { get; set; }
}
public class CreateItemCommandHandler : IRequestHandler<CreateItemCommand, int>
{
private readonly IMapper _mapper;
private readonly IDbContext _context;
public CreateItemCommandHandler(IDbContext context, IMapper mapper)
{
_mapper = mapper;
_context = context;
}
public async Task<int> Handle(CreateItemCommand request, CancellationToken cancellationToken)
{
var entity = _mapper.Map<Item>(request);
_context.Items.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
CreateManyItems
you might want to use the termBatchCreateItems
. It conveys the same information, and batch processing is indeed a valid strategy for creating several items at once.