插入后映射外键对象



插入新记录时,要求返回一个DTO,其中包含一个简化FK对象或一个完整的FK对象,包含在预期输出中。

问题是相关对象ExampleOptionDto和ExampleOptionSimpleDto始终为null。

我做错了什么?

//预期输出

{
"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
}

你所写的一切对我来说都很有意义,我只有两个建议

1(调试命令处理程序。特别是中每个值中存储的内容

ExampleEntity entity = Mapper.Map<Command, ExampleEntity>(command);
await Db.ExampleEntity.AddAsync(entity, cancellationToken);
await Db.SaveChangesAsync(cancellationToken);

ExampleDto model = Mapper.Map<ExampleEntity, ExampleDto>(entity);

2.尝试添加另一个从dto到实体的映射

CreateMap<ExampleDto ,ExampleEntity>();

最新更新