Skip to content

Factories

Ushakov Michael edited this page Nov 9, 2025 · 3 revisions

Introduction

In any case, our applications interact with the real world by means of DTO. Even when we are dealing with the SimplifiedModelManager without explicit DTO we also have a DTO that is an entity class. Simply factories = service classes that are used to map DTO to Entity class and back.

Why we are using Factories:

  1. Representation could have differences with the Entity class, i.e., hide some fields.
  2. DTO could enrich some Entity object with additional data.

All below methods are actual for a Manager classes based on EntityFramework

1 Create DTO from Entity

Manager classes implies that we are going to pass Func<TObj, TRes> for the conversion TObj (Entity class) to TRes (DTO) . See example of a conversion Entity to DTO here

2 Create Entities from DTO

Default implementation of Create and Update methods implies data contract with class deriving from the DbContext class

2.1 Create Entity from DTO

For building a newly created database object from DTO we have to pass DTO itself and DbContext that is used for setting up many-2-many relations during a database object creation, see the example In the upper linked example, we are setting up assigned Roles to User by passing a list of role identifiers in the DTO:

if (dto.Roles != null)
{
    entity.Roles = dbContext.Roles.Where(r => dto.Roles.Contains(r.Id)).ToList();
}

2.2 Update Entity from DTO

This delegate is using for update an already got database object it also receives DTO and, additionally, an object identifier, DbContext and entity class for update, see this example during the update we are setting up new many-2-many relations:

if (dto.Roles != null)
{
    entity.Roles = dbContext.Roles.Where(r => dto.Roles.Contains(r.Id)).ToList();
}
Clone this wiki locally