亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 AutoMapper 添加、更新和刪除 List 中的項目

使用 AutoMapper 添加、更新和刪除 List 中的項目

C#
Qyouu 2022-07-23 17:38:07
AutoMapper 是否沒有本地方法來更新需要刪除、添加或更新實例的嵌套列表?我在帶有 EF Core 的 ASP.Net Core 應用程序中使用 AutoMapper 將我的 API 資源映射到我的模型。這對我的大多數應用程序來說都運行良好,但我對更新映射嵌套列表的解決方案不滿意,其中列出的實例需要保留。我不想覆蓋現有列表,我想刪除傳入資源中不再存在的實例、添加新實例并更新現有實例。型號:public class MainObject{    public int Id { get; set; }    public List<SubItem> SubItems { get; set; }    }public class SubItem{    public int Id { get; set; }    public int MainObjectId { get; set; }    public MainObject MainObject { get; set; }    public double Value { get; set; }}資源:public class MainObjectResource{    public int Id { get; set; }    public ICollection<SubItemResource> SubItems { get; set; }    }public class SubItemResource{    public int Id { get; set; }    public double Value { get; set; }}控制器:public class MainController : Controller{    private readonly IMapper mapper;    private readonly IMainRepository mainRepository;    private readonly IUnitOfWork unitOfWork;    public MainController(IMapper mapper, IMainRepository mainRepository, IUnitOfWork unitOfWork)    {        this.mapper = mapper;        this.mainRepository = mainRepository;        this.unitOfWork = unitOfWork;    }    [HttpPut("{id}")]    public async Task<IActionResult> UpdateMain(int id, [FromBody] MainObjectResource mainObjectResource)    {        MainObject mainObject = await mainRepository.GetMain(id);        mapper.Map<MainObjectResource, MainObject>(mainObjectResource, mainObjectResource);        await unitOfWork.CompleteAsync();        return Ok();     }}
查看完整描述

3 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

我開始查看AutoMapper.Collection,這確實是我希望找到的擴展。實施后,我的列表會按照我的意愿進行更新。配置在我的使用中很簡單,因為我只需要指定我的對象的 ID。


我的啟動配置改為:


using AutoMapper;

using AutoMapper.EquivalencyExpression;

[....]

        public void ConfigureServices(IServiceCollection services)

        {

            services.AddAutoMapper(cfg => {

                cfg.AddCollectionMappers();

                });

        }

[....]

還有我的映射配置文件:


    CreateMap<SubItem, SubItemResource>().ReverseMap()

        .EqualityComparison((sir, si) => sir.Id == si.Id);


查看完整回答
反對 回復 2022-07-23
?
MM們

TA貢獻1886條經驗 獲得超2個贊

這是一個比表面上看起來更難解決的問題。對您的列表進行自定義映射很容易,因為您了解您的應用程序;AutoMapper 沒有。例如,是什么使源項等于目標項,以便 AutoMapper 能夠辨別它應該映射現有的而不是添加的?PK?哪個屬性是PK?該屬性在源和目標上是否相同?這些是您可以在 .AutoMapper 中輕松回答的問題AfterMap,而不是 AutoMapper。

因此,AutoMapper 總是將集合映射為新項目。如果這不是你想要的行為,那就是這樣的事情AfterMap。還要記住,AutoMapper 并不是專門為與 EF 一起使用而設計的,這才是真正的問題,而不是 AutoMapper。EF 的更改跟蹤是導致 AutoMapper 的默認集合映射行為出現問題的原因。在其他情況和場景中,這不是問題。


查看完整回答
反對 回復 2022-07-23
?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

我相信我已經實現了一個配置,其中我的 InputModels 和 EntityClasses 可以包含一個 Id,我只需要創建一個映射配置文件并調用:Mapper.Map(inputModelClassInstance, entityClassInstance);


因此 AutoMapper 和 EF CORE 將使用我的實例的 Id 來查看它們是否相等并按預期添加、刪除或更新。


這是我所做的:


我用過:https ://github.com/AutoMapper/Automapper.Collection.EFCore


(鏈接中的修改代碼):


var services = new ServiceCollection();

services

    .AddEntityFrameworkSqlServer() //Use your EF CORE provider here

    .AddDbContext<MyContext>(); //Use your context here


services.AddAutoMapper((serviceProvider, automapper) =>

{

    automapper.AddCollectionMappers();

    automapper.UseEntityFrameworkCoreModel<MyContext>(serviceProvider);

}, typeof(DB).Assembly);


var serviceProvider = services.BuildServiceProvider();

然后我CreateMap<>()的看起來像這樣:


CreateMap<InputModelClass, EntityClass>(MemberList.Source);

CreateMap<ChildInputModelClass, ChildClass>(MemberList.Source);

我只需通過以下方式執行更新:


//Fetch entityClassInstance from db:

var entityClassInstance = Context.EntityClasses

.Where(ec => ex.id == id)

.Include(ec => ec.children)

.FirstOrDefault();


//Perform update:

Mapper.Map(inputModelClassInstance, entityClassInstance);

我可以在父子集合中添加和刪除,EF CORE + AutoMapper 將按預期添加、刪除和更新。


我相信.UseEntityFrameworkCoreModel<MyContext>(serviceProvider)添加了 AutoMapper 將使用 Ids 來比較要添加、刪除和更新的配置。


重要提示:包含子實體非常重要,否則 AutoMapper 不會更新它們。


查看完整回答
反對 回復 2022-07-23
  • 3 回答
  • 0 關注
  • 293 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號