[英]AutoMapper setting EF entity ID to 0 during mapping
我有一個Character
實體和一個CharacterDto
,如下所示:
特點
public class Character
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int Health { get; set; } = 100;
public int Defense { get; set; } = 10;
public int Strength { get; set; } = 10;
public int Intelligence { get; set; } = 10;
public RpgClass Class { get; set; }
}
字符Dto
public class CharacterDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int Health { get; set; }
public int Defense { get; set; }
public int Strength { get; set; }
public int Intelligence { get; set; }
public RpgClass Class { get; set; }
}
我有一個CharacterMappingProfile
class 配置我的Character
和DTO
映射:
CreateMap<CharacterDto, Character>()
.ForMember(
dest => dest.Id,
opt => opt.Ignore()
);
我正在嘗試將CharacterDto
中存在的值 map 到我使用 EntityFramework 從數據庫重試的現有Character
實體上。
var character = _context.FirstOrDefaultAsync(...);
character = _mapper.Map<Character>(dto);
在執行 map 之前, character
具有有效的Id
屬性。 但是,在 map 之后,值為0
,這不是我想要的。 我希望 AutoMapper 忽略該屬性,並因此保留數據庫中的任何值。 我一定是誤解了Ignore
的ForMember
是如何工作的,因為我認為這樣可以解決問題。
我是否錯誤地配置了我的映射,或者我在其他地方出錯了?
到 map 一個CharacterDto
到一個現有的Character
object 你需要使用:
var character = _context.FirstOrDefaultAsync(...);
_mapper.Map(dto, character);
現在_mapper.Map<Character>(dto);
將您的 dto 映射到一個新的空Character
實例,然后將其分配給字符變量。 這就是Id
屬性為 0 的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.