【发布时间】:2021-04-08 13:53:43
【问题描述】:
插入新记录时,要求返回一个 DTO,其中包含在预期输出中的简化 FK 对象或完整 FK 对象。
问题是相关对象 ExampleOptionDto 和 ExampleOptionSimpleDto 总是为空。
我做错了什么?
// 预期输出
{
"Id": 45,
"Name": "Example...",
"ExampleOptionSimple": {
"Id": 45,
"Name": "Example Option 7"
},
"ExampleOption": {
"Id": 45,
"Name": "Example Option 7",
"Acronym": "",
...
}
}
// 创建处理程序
public class Create
{
public class Command : IRequest<ExampleDto>
{
public string Name { get; set; }
public int ExampleOptionId { get; set; }
}
public class Handler : BaseHandler, IRequestHandler<Command, ExampleDto>
{
public Handler(ApplicationContext db, IMapper mapper, IUserContext userContext) : base(db, mapper, userContext) {}
public async Task<ExampleDto> Handle(Command command, CancellationToken cancellationToken)
{
ExampleEntity entity = Mapper.Map<Command, ExampleEntity>(command);
await Db.ExampleEntity.AddAsync(entity, cancellationToken);
await Db.SaveChangesAsync(cancellationToken);
ExampleDto model = Mapper.Map<ExampleEntity, ExampleDto>(entity);
return model;
}
}
}
// DTO
public class ExampleDto
{
public int Id { get; set; }
public string Name { get; set; }
public int ExampleOptionId { get; set; }
// Use this to return a simple related model with just Id & Name
public ExampleOptionSimpleDto ExampleOptionSimple { get; set; }
// Use this to return the full related object and all properties
public ExampleOptionDto ExampleOption { get; set; }
}
public class ExampleOptionDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Acronym { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
public Guid? DeletedBy { get; set; }
}
public class ExampleOptionSimpleDto
{
public int Id { get; set; }
public string Name { get; set; }
}
// 映射
CreateMap<ExampleOption, ExampleOptionSimpleDto>();
CreateMap<ExampleOption, ExampleOptionDto>();
CreateMap<ExampleEntity, ExampleDto>();
// 测试
[Theory]
[ClassData(typeof(CreateTestData))]
public async Task Create_Adds_Record_To_Store_And_Returns_It(Create.Command cmd)
{
// Create a new record
ExampleDto exampleDto = await _fixture.SendAsync(cmd, _accessor);
exampleDto.ShouldNotBeNull(); // Passes
exampleDto.Id.ShouldBe(1); // Passes
exampleDto.ExampleOption.ShouldNotBeNull(); // Fails
exampleDto.ExampleOptionSimple.ShouldNotBeNull(); // Fails
}
【问题讨论】:
标签: c# automapper mediatr