2

I'm using Mapster to map Dto instances to Model objects.

The Dtos are sent by a Javascript client, sending only the properties updated.

I would like to ignore null values, and have Mapster leave the model instance unchanged for this properties.

A simplified example to better explain the scenario:

// My .Net Dto class, used for client/server communication.
public class PersonDto
{
  public string Id { get; set; }
  public string Name { get; set; }
  public string Family { get; set; }
}

// My Model class. Let's assume is the same data as per the Dto.
public class Person
{
  public string Id { get; set; }
  public string Name { get; set; }
  public string Family { get; set; }
}

public void Update()
{
  var existingPerson = new Person
  {
    Id = "A",
    Name = "Ned",
    Family = "Stark"
  };

  var patchDataSentFromClient = new PersonDto
  {
    Id = "A",
    Name = "Rob"
  };

  patchDataSentFromClient.Adapt(existingPerson);

  // Here existingPerson.Family should be "Stark", but it gets emptied out.
  // the mapping should be equivalent to:
  // if (patchDataSentFromClient.Family != null) existingPerson.Family = patchDataSentFromClient.Family;
}

Edit: the point is I don't want to write down the mapping condition for each of the thousands of properties in my Dtos. I want Mapster to Automap all string properties by name, but keep the "patch-like" logic of ignoring null values.

4

1 回答 1

5

您可以使用IgnoreNullValues

于 2017-02-14T04:13:51.620 回答