c# Automapper - Sequence of Properties

489 Views Asked by At

Classes created as below:

public class Base
{
   public int Id { get; set; }
}
public class Derived:Base
{
   public string Name { get; set; }
}

Automapper mapping defined as:

CreateMap<DataRow, Base>()
.ForMember(m => m.Id, opt => opt.MapFrom(r => r["Id"]));

CreateMap<DataRow, Derived>()
.IncludeBase<DataRow, Base>()
.ForMember(m => m.Name, opt => opt.MapFrom(r => r["Name"]))

Output of this mapping is:

{
 "Name":"ABC",
 "Id":1
}

Expected result:

{
 "Id":1,
 "Name":"ABC"
}

I want to maintain the sequence of properties as defined in base and derived class.

1

There are 1 best solutions below

0
On BEST ANSWER

This has nothing to do with Automapper, that library doesn't affect the JSON serialisation.

The real issue is that you have a derived class. Serialisation libraries use reflection to get the properties and that starts with the properties in the derived class and works up the hierarchy. You can see this with this code:

var props = string.Join(", ", typeof(Derived).GetProperties().Select(x => x.Name));

//props = "Name, Id"

However, you can control the serialisation with some attributes. If you are using .NET 3+, then you will likely be using the System.Text.Json namespace. That means you can change your model to be something like this:

using System.Text.Json.Serialization;

public class Base
{
    [JsonPropertyOrder(1)]
    public int Id { get; set; }
}
public class Derived : Base
{
    [JsonPropertyOrder(2)]
    public string Name { get; set; }
}

Alternatively, you may be using Newtonsoft JSON.Net which means your models will instead look like this:

using Newtonsoft.Json;

public class Base
{
    [JsonProperty(Order = 1)]
    public int Id { get; set; }
}
public class Derived : Base
{
    [JsonProperty(Order = 2)]
    public string Name { get; set; }
}