我想使用 AutoMapper 將帶有嵌套串列的 EntityDto 映射到物體,然后使用 SaveChanges() 呼叫更新它。
問題是 AutoMapper 將嵌套的 List 元素映射為新物件,因此 EntityFramework 認為我想添加具有現有 Id 的新物件。
例子:
public class Entity
{
public Guid Id { get; set; }
public List<NestedEntity> NestedEntityList { get; set; }
}
public class EntityDto
{
public Guid Id { get; set; }
public List<NestedEntityDto> NestedEntityList { get; set; }
}
public class NestedEntity
{
public Guid Id { get; set; }
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}
public class NestedEntityDto
{
public Guid Id { get; set; }
public string PropertyTwo { get; set; }
}
例如,物體有一個包含 2 個 NestedEntity 物件的串列
{
"Id": "EntityId"
"NestedEntityList": [
{
"Id": "A",
"PropertyOne": "Value A",
"PropertyTwo": "Value AA"
},
{
"Id": "B",
"PropertyOne": "Value B",
"PropertyTwo": "Value BB"
}
]
}
更新:(A 修改,B 洗掉,C 添加)
EntityDto 有一個包含 2 個 NestedEntity 物件的串列
{
"Id": "EntityId"
"NestedEntityList": [
{
"Id": "A",
"PropertyTwo": "Value AAA (Updated)"
},
{
"Id": "C",
"PropertyTwo": "Value CC"
}
]
}
無需進一步配置 AutoMapper 通過創建新物件來映射 NestedEntityList。這導致2個問題:
- EntityFramework 會將這些新物件作為新創建的物件而不是已更新的現有物件進行跟蹤。這會導致以下錯誤訊息:“無法跟蹤物體型別“NestedEntity”的實體,因為已跟蹤具有鍵值“A”的另一個實體”。
- 如果NestedEntity 有PropertyOne 值,那么映射后就會為null,因為NestedEntityDto 沒有PropertyOne。我想更新 EntityDto(即 PropertyTwo)中的屬性并保留其他所有內容的值。
所以我想達到的結果:(A修改,B洗掉,C添加)
{
"Id": "EntityId"
"NestedEntityList": [
{
"Id": "A",
"PropertyOne": "Value A", //Old value, not updated with NULL
"PropertyTwo": "Value AAA (Updated)" //Updated value
},
{
"Id": "C", //New item added in the update
"PropertyOne": NULL,
"PropertyTwo": "Value CC"
}
]
}
我需要如何配置 AutoMapper 來實作這一點?有可能嗎?
uj5u.com熱心網友回復:
映射到現有集合時,首先清除目標集合。如果這不是您想要的,請查看AutoMapper.Collection。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365814.html
