簡體   English   中英

AutoMapper 在映射期間將 EF 實體 ID 設置為 0

[英]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 配置我的CharacterDTO映射:

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 忽略該屬性,並因此保留數據庫中的任何值。 我一定是誤解了IgnoreForMember是如何工作的,因為我認為這樣可以解決問題。

我是否錯誤地配置了我的映射,或者我在其他地方出錯了?

到 map 一個CharacterDto到一個現有的Character object 你需要使用:

var character = _context.FirstOrDefaultAsync(...);
_mapper.Map(dto, character);

現在_mapper.Map<Character>(dto); 將您的 dto 映射到一個新的空Character實例,然后將其分配給字符變量。 這就是Id屬性為 0 的原因。

Automapper:更新屬性值而不創建新的 object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM