John S
John S

Reputation: 8349

Using Mapster to map from flat model to a model with nested properties in TypeAdapterConfig

Using EF Core 3 and Mapster I would like to map from a flat dto object to an object with a related sub-object. i.e.

_ = TypeAdapterConfig<NoteVM, Note>.NewConfig()
            .Map(d => d.Detail, s => s.Description)
            .Map(d => d.Id, s => s.NoteId)
            .Map(d => d.NoteTypeObject, s => s.NoteTypeString)
            .IgnoreNullValues(true);

Where NoteTypeObject is an existing record on a table.

So in the mapping the NoteType object has to be retrieved from the db and attached to the Note record before the Note record is saved.

Can this be done in the config section or does this need to be done after the mapping but before the Note object is saved to the DB?

Upvotes: 1

Views: 5253

Answers (1)

hanzolo
hanzolo

Reputation: 1150

In the mapping of the NoteType, the object has to be retrieved from the db and attached to the Note record before the Note record is saved. So to do this, create an additional function to load the object from the database such as "GetNoteTypeId(..)" which will retrieve the object from the DB and attach it.

_ = TypeAdapterConfig<NoteVM, Note>.NewConfig()
        .Map(d => d.Detail, s => s.Description)
        .Map(d => d.Id, s => s.NoteId)
         //get existing Id
        .Map(d => d.NoteTypeObjectId, s => GetNoteTypeId(s.NoteTypeString))//lookup 

        .IgnoreNullValues(true);

If you are able to add a reference ID instead of object reference you can do something like the above.

Upvotes: -1

Related Questions