How to expose part of Entity as DataContract?

后端 未结 2 1757
粉色の甜心
粉色の甜心 2021-01-20 17:40

Up to now, when working with WCF, I have always been exposing the whole either EF generated entities, or POCOs(by modifying the T4 template to include DataContract and DataM

相关标签:
2条回答
  • 2021-01-20 18:04

    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);
    
    0 讨论(0)
  • 2021-01-20 18:24

    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.

    0 讨论(0)
提交回复
热议问题