无隐式引用从'System.Collections.Generic.List '到'MediatR.IRequest '+ .NET Core + CQRS

问题描述 投票:0回答:1

我正在API控制器方法中获得一个List,并将其传递给Handler,如下所示。我打算做的是遍历列表,并将列表中的所有项目保存到数据库中。

public class Create
{
    public class Command : IRequest
    {
        public Guid A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
        public bool D { get; set; }
    }

    public class Handler : IRequestHandler<List<Command>>
    {
        private readonly DataContext _context;
        private readonly IMapper _mapper;
        public Handler(DataContext context, IMapper mapper)
        {
            _mapper = mapper;
            _context = context;
        }

        public async Task<Unit> Handle(List<Command> request, CancellationToken cancellationToken)
        {
            // loop over the request list and save in the database
        }
    }
}

但是在代码行Handler中的[public class Handler : IRequestHandler<List<Command>>]下有一个红线。

悬停在[Handler]上,它说:

类型'System.Collections.Generic.List'不能在通用类型中用作类型参数“ TRequest”,或方法“ IRequestHandler”。没有隐式引用转换自'System.Collections.Generic.List'到“ MediatR.IRequest”。 [应用程序] csharp(CS0311)

我的API控制器方法是:

[HttpPost]
public async Task<ActionResult<Unit>> Create(List<Create.Command> commands) // not like this, it'll be a list
{
     return await Mediator.Send(commands);
}

return await Mediator.Send(commands);下的红线说:

无法将类型'object'隐式转换为'Microsoft.AspNetCore.Mvc.ActionResult'。一个明确的转换存在(您是否缺少演员表?)[API] csharp(CS0266)

[如果我在写问题时错过了一些信息,请放心,我会在询问时不断更新。

c# rest asp.net-core cqrs mediatr
1个回答
0
投票

步骤1:在Command类中没有嵌套,而在Command类所在的同一Create.cs类中有一个嵌套类:

    public class CreateDto
    {
        public Guid A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
        public bool D { get; set; }
    }

步骤2:将是Command类。您的Command类现在为:

    public class Command : IRequest
    {
        public List<CreateDto> SomeObjects { get; set; }
    }

步骤3:处理程序类将变为:

public class Handler : IRequestHandler<Command>
    {
        private readonly DataContext _context;
        private readonly IMapper _mapper;
        public Handler(DataContext context, IMapper mapper)
        {
            _mapper = mapper;
            _context = context;
        }

        public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
        {
            foreach (var obj in request.SomeObjectss)
            {
                // logic
            }
            return Unit.Value;
        }
    }

步骤4:控制器方法将变为:

    [HttpPost]
    public async Task<ActionResult<Unit>> Create(List<CreateDto> createDtos)
    {
        return await Mediator.Send(new Create.Command{SomeObjects = createDtos});
    }
© www.soinside.com 2019 - 2024. All rights reserved.