-
Notifications
You must be signed in to change notification settings - Fork 8
Factories
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:
- Representation could have differences with the
Entityclass, i.e., hide some fields. -
DTOcould enrich some Entity object with additional data.
All below methods are actual for a Manager classes based on EntityFramework
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
Default implementation of Create and Update methods implies data contract with class deriving from the DbContext class
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();
}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();
}