当谈到 C# 中的对象关系映射时,许多人会立即想到 AutoMapper。事实上,AutoMapper 是一个出色的对象映射库。
但是,今天我想分享另一个我个人认为更轻量级、更有用的库:Mapster。虽然它的受欢迎程度可能不如 AutoMapper 高,但它的力量是不可否认的。
<PackageReference Include="Mapster" Version="7.4.0" />
定义一个简单的实体类 ,如下所示:Person
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
定义用于数据传输的 DTO 类,如下所示:PersonDto
public class PersonDto
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public DateTime CreatedAt { get; set; }
}
为了计算年龄,您需要一种辅助方法。此步骤不是必需的:
/// <summary>
/// Calculate age based on date of birth.
/// </summary>
/// <param name="dateOfBirth"></param>
/// <returns></returns>
public static int CalculateAge(DateTime dateOfBirth)
{
return (DateTime.Today.Year - dateOfBirth.Year) - ((DateTime.Today.Month < dateOfBirth.Month) ? 1 : 0);
}
在 中,使用 Mapster 的 static 方法执行对象映射:Program.csAdapt
// Configure Mapster mapping rules.
// By default, Mapster will match based on the same field names of the two entities.
// So if there are two classes with the same field names, Mapster will automatically map the property values of one class to the corresponding properties of the other.
// When more complex object mapping is needed, you need to configure it through `TypeAdapterConfig`.
// For example, you can define custom mapping rules, specifying how to map from the source object to the target object. This allows you to flexibly control the details of the mapping process.
TypeAdapterConfig<Person, PersonDto>
.NewConfig()
.Map(dest => dest.FullName, src => $"{src.FirstName}{src.LastName}")
.Map(dest => dest.Age, src => CalculateAge(src.DateOfBirth))
.AfterMapping((src, dest) =>
{
// Custom logic, such as adding additional information.
dest.CreatedAt = DateTime.Now;
});
// Create a Person entity object.
var person = new Person {
Id = 1,
FirstName = "Jacky",
LastName = "Yang",
DateOfBirth = new DateTime(1990, 1, 1)
};
// Use Mapster to map the person object to the PersonDto type.
var personDto = person.Adapt<PersonDto>();
// Output the mapping result.
Console.WriteLine($"Full Name:{personDto.FullName}");
Console.WriteLine($"Age:{personDto.Age}");
Console.WriteLine($"Created At:{personDto.CreatedAt}");
Console.ReadKey();
编译并运行程序,您将看到对象已成功转换为对象,并且包括 custom 和 fields。PersonPersonDtoFullNameAge
Mapster 和 AutoMapper 都非常适合在 DTO(数据传输对象)和实体之间进行映射,从而简化代码并提高开发效率。但是,Mapster 具有以下优点:
var personDto = person.Adapt<PersonDto>();
这种简单性使 Mapster 在实际开发中非常方便。
使用 Mapster 时,请考虑以下建议:
怎么样?您不认为 Mapster 比 AutoMapper 更方便、更用户友好吗?是真的!
虽然 AutoMapper 提供的功能比 Mapster 更多,但在合适的场景中,Mapster 更轻、更高效、更容易学习。