出现此问题的主要原因是由于最新的版本速度更快而从 AutoMapper 更改为 Mapperly。我遇到的问题是我不知道如何自动将 UpdateBarDTO 映射到 Bar,忽略...
出现这个问题的主要原因是由于最新的版本速度更快,所以从 AutoMapper 改为 Mapperly。
我遇到的问题是我不知道如何自动将 Update的 idDTO 到 Bar Bar Bar ,以便它修改正确的数据库对象而不会出现错误:
System.InvalidOperationException: The property 'Bar.Id' is part of a key and so cannot
be modified or marked as modified. To change the principal of an existing entity with an
identifying foreign key, first delete the dependent and invoke 'SaveChanges',
and then associate the dependent with the new principal.
public record class UpdateBarDTO
(
[Required][StringLength(255)] string Name,
[Required] string Address,
[Required] string PhoneNumber,
[Required] string Email,
string Website,
string CuisineType,
[Required] string OpeningHours,
DateTime CreationDate
);
public class Bar
{
public int Id { get; set; }
public required string Name { get; set; }
public required string Address { get; set; }
public required string PhoneNumber { get; set; }
public required string Email { get; set; }
public string? Website { get; set; }
public string? CuisineType { get; set; }
public required string OpeningHours { get; set; }
public DateTime? CreationDate { get; set; }
}
我已设法通过以下方法找到解决方案:使用 UpdateBarFromDto() 设置 id,以便数据库知道要更新哪个对象
[Mapper]
public partial class BarMapper
{
public partial Bar ToUpdateBar(UpdateBarDTO bar);
public Bar UpdateBarFromDto(UpdateBarDTO updateBarDTO, Bar bar)
{
var dto = ToUpdateBar(updateBarDTO);
dto.Id = bar.Id;
return dto;
}
有效载荷:仅名称发生变化
PUT <http://localhost:5294/bars/1>
Content-Type: application/json
{
"Name": "Sunset Lounge Skyy",
"Address": "123 Ocean Drive, Miami, FL 33139",
"PhoneNumber": "305-555-1234",
"Email": "[email protected]",
"Website": "<http://www.sunsetlounge.com>",
"CuisineType": "Seafood",
"OpeningHours":"Monday: 10:00 AM - 11:00 PM,Tuesday: 10:00 AM - 11:00 PM,Wednesday: 10:00 AM - 11:00 PM,Thursday: 10:00 AM - 11:00 PM,Friday: 10:00 AM - 12:00 AM,Saturday: 10:00 AM - 12:00 AM,Sunday: 10:00 AM - 10:00 PM",
"CreationDate": "2020-08-15T00:00:00"
}
控制器
//PUT /bars/1
group.MapPut("/{id}", async (int id, UpdateBarDTO updatedBar, ServitusDbContext dbContext) =>
{
var existingBar = await dbContext.Bars.FindAsync(id);
if (existingBar is null)
return Results.NotFound();
//set the id of updatedBarDTO
var bar = new BarMapper().UpdateBarFromDto(updatedBar, existingBar);
//locate the bar you want to update, map it to DTO and set the values
dbContext.Entry(existingBar)
.CurrentValues
.SetValues(bar);
await dbContext.SaveChangesAsync();
return Results.NoContent();
});
对于那些了解 AutoMapper 的人来说,我希望实现与此相同的效果:
var bar = mapper.Map<UpdateBarDTO, Bar>(updatedBar, opt => opt.AfterMap((src, dest) => dest.Id = id));
非常感谢!