How to expose part of Entity as DataContract?

Deadly 提交于 2019-12-02 00:13:46

I would go with option 1 -> AutoMapper.

it does not work as it cannot do a two way mapping.

You could define two way mapping:

Mapper.CreateMap<Product, ProductContract>();
Mapper.CreateMap<ProductContract, Product>();

obviously if in your ProductContract you have less properties than in your domain model when doing the mapping, only the corresponding properties will be populated.

When doing the inverse map for updating you could do the following:

ProductContract pc = ...
Product productToUpdate = GetProduct(pc.Id);
Mapper.Map<ProductContract, Product>(pc, product);
// at this stage the product model will have the properties that
// were present in the ProductContract being mapped from them and
// the rest of the properties will stay unmodified, i.e. they will
// have their initial values that were retrieved from the database.
// Now we can update the product:
UpdateProduct(product);

First of all you should never expose the whole entity as a data contract, as it is a domain object, not the data transfer object. Not just in that particular situation. Never. Now you're creating a confusing inconsistency between entities which do have a DTO and those which don't.

Returning to a question: AutoMapper seems to be pretty ok. You just have to define 2 mappings. And probably Ignore() missing properties when mapping back to entity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!