使用AutoMapper和EFCore进行TrackingChanges时,将DTO映射到实体

时间:2017-06-07 14:49:58

标签: c# asp.net .net entity-framework automapper

对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);

}

1 个答案:

答案 0 :(得分:0)

您可以创建适配器类,以使更改集保持不变: 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);
    }
}