您可以创建一个适配器类,以便您的更改集保持不变:
你有没有从接口继承 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
}
编辑
Children 工作正常,只需使用相同的适配器模式,setter 的代码很多,但是
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);
}
}