Skip to content

Mapping Graphs

Leonardo Porro edited this page Dec 16, 2022 · 36 revisions

This library allows to map data directly into an entity graph and set the right state for each entity automatically.

The type of the data to be mapped can be the same entity, any other class or anonymous type with a similar structure or dynamic objects like a dictionary or json.

Entity graph consists of the main entity to be updated along a subset of its related entities.

Same way as in GraphDiff, when a mapping is performed, an entity graph is loaded, then input data is mapped on it and the right states are set. Return value is the root entity of the loaded graph, ready to be saved by the next call to DbContext.SaveChanges.

You may think this library as a combination of GraphDiff and a very basic AutoMapper.

Choose the input data

Mapping from the same entity

The same entity type can be used as input data for mapping.

User user = await _dbContext.MapAsync<User>(new User { Id = 1, Name = "user name" });
Mapping from a DTO

Usually, entities are too complex or contain sensitive data and cannot be exposed as method inputs, so DTOs are the recommended way. Also, the goal of the library is to create as many DTOs as needed without worrying about mapping them. Some APIs, especially GraphQL ones have one input DTO per operation: SaveUser(SaveUserInput input);

User user = await _dbContext.MapAsync<User>(new UserDTO { Id = 2, Name = "user name" });
Mapping from an anonymous type
User user = await _dbContext.MapAsync<User>(new { Id = 3, Name = "user name" });
Mapping from a dictionary
User user = await _dbContext.MapAsync<User>(new Dictionary<string, object> { { "Id", 4 }, { "Name", "user name" });
Mapping from Json

Define a Graph subset