Repository pattern and mapping between domain models and Entity Framework

后端 未结 6 1179
后悔当初
后悔当初 2020-12-04 07:15

My repositories deal with and provide persistence for a rich domain model. I do not want to expose the anemic, Entity Framework data entity to my business layers, so I need

6条回答
  •  遥遥无期
    2020-12-04 07:48

    My repositories deal with and provide persistence for a rich domain model. I do not want to expose the anemic, Entity Framework data entity to my business layers, so I need some way of mapping between them.

    If you you use Entity Framework, it can map Rich Domain Model itself.

    I've answered the similar question "Advice on mapping of entities to domain objects" recently.

    I've been using NHibernate and know that in Entity Framework you can also specify mapping rules from DB tables to your POCO objects. It is an extra effort to develop another abstraction layer over Entity Framework entities. Let the ORM be responsible for all of the mappings, state tracking, unit of work and identity map implementation, etc. Modern ORMs know how to handle all these issues.

    AutoMapper could be used for the opposite situation (mapping to data entities) but not when creating domain models.

    You are completely right.

    Automapper is useful when one entity can be mapped into another without additional dependencies (e.g. Repositories, Services, ...).

    ... where would I define the mapping between a Department and a DepartmentDataEntity?

    I would put it into DepartmentRepository and add method IList FindByCompany(int companyId) in order to retreive company's departments.

    I could provide more mapping methods in the CompanyRepository, but this will soon get messy. There would soon be duplicated mapping methods across the system.

    What is a better approach to the above problem?

    If it is needed to get list of Departments for another entity, a new method should be added to DepartmentRepository and simply used where it is needed.

提交回复
热议问题