簡體   English   中英

使用AutoMapper和EFCore跟蹤更改時將DTO映射到實體

[英]Mapping DTO to Entity while TrackingChanges with AutoMapper and EFCore

對AutoMapper和EFCore來說是非常新的東西,所以也許比我在這里所能做的要多得多,但我想我可以嘗試一下,但是失敗了,也許沒有可能,但是如果有人可以指出我正確的方向。

我正在使用AutoMapper將我的實體轉換為DTO,這很好。

現在我想將我的DTO轉換為一個實體,並讓EntityFramework跟蹤所有更改(屬性更新,從列表中刪除子對象等),但是這可能嗎?

因此,如果我有一個簡單的PUT方法,我想做這樣的事情,然后讓automapper整理其余的內容

public async Task<IActionResult> PutAsync([FromBody] MyDTO model)
{
    // GET OBJECT FROM DATABASE HERE
    var dbValue = _repos.GetMyObjectUsingId(999);

    // apply updates
    _mapper.Map<MyDTO, MyObject>(dbValue, model);

}

您可以創建一個適配器類,以便您的更改集保持不變:您是否從接口繼承了DTO?

假設您有一個DTO:

public interface IFooDTO
{
   int Id { get; set;}
   string Name { get; set;}
}

public class FooDTO : IFooDTO
{
   public int Id { get; set;}
   public string Name { get; set; }
}

然后你有你的實體

public class FooEntity
{
   public int Id;
   public string name;
}

然后像這樣創建您的適配器,該適配器繼承自foo接口:

public class FooAdapter : IFooDTO
{
   FooEntity entity;
   FooAdapter(FooEntity entity)
   {
      this.entity = entity;
   }

   public int Id 
   {
      get {return this.entity.Id;}
      set {/*Do nothing set by EF*/}
   }

   public string Name
   {
       get {return this.entity.Name;}
       set {this.entity.Name = value; }
   }

   public void Apply(FooDTO foo)
   {
        //I don't remember if this is the correct order but you get the gyst
        this._mapper.Map<IFooDTO, IFooDTO>(this, foo);
   }
}

然后,您只需要在映射器中將您的Idto映射到您的dto。

用法:

 public ActionResult PutFoo(int id, FooDTO foo)
 {
     var entity = context.Foos.FirstOrDefault(x => x.Id == id);
     var adapter = new FooAdapter(entity);
     adapter.Apply(foo);
     //Entity has been updated and has original changes
 }

編輯

兒童工作正常,只是使用相同的適配器模式,因此設置程序的設置很多,但是

public BarDTO childBar
{
   get { return new BarAdapter(this.entity.Bar).ToDTO(); }
   set { new BarAdapter(this.entity.Bar).Apply(value) }
}

同步實體:

public static void Sync<TEntity, TEntityKey, TDTO>(this ICollection<TEntity> entityCollection, ICollection<TDTO> dtoCollection,
    Func<TEntity> entityConstructor, Action<TDTO, TEntity> copyAction,
    Action<TEntity> onDeleteAction,
    Func<TEntity, TEntityKey> entityKeySelector, 
    Func<TDTO, TEntityKey> dtoKeySelector)
    where TEntity : class
    where TEntityKey : struct
{
    dtoCollection = dtoCollection ?? new TDTO[] { };
    except = except ?? new TEntityKey[] { };

    var dtoIds = dtoCollection.Select(dto => dtoKeySelector(dto)).ToHashSet();
    foreach (var entity in entityCollection.Where(x => false == dtoIds.Contains(entityKeySelector(x))).ToArray())
    {
        onDeleteAction(entity);
        entityCollection.Remove(entity);
    }

    var entityCollectionMap = entityCollection.ToDictionary(x => entityKeySelector(x));

    foreach (var dtoItem in dtoCollection)
    {
        TEntity entity = null;
        if (dtoKeySelector(dtoItem).HasValue)
        {
            entity = entityCollectionMap.ContainsKey(dtoKeySelector(dtoItem)) ? entityCollectionMap[dtoKeySelector(dtoItem)] : default(TEntity);

        }

        if (null == entity)
        {
            entity = entityConstructor();
            entityCollection.Add(entity);
        }
        copyAction(dtoItem, entity);
    }
}

暫無
暫無

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

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