如何使用 AutoMapper 将 POCO 映射到 Record

How to map POCO into Record using AutoMapper

我将 AutoMapper 10.1.1 与 .NET 6(预览版)和 C# 10 一起使用。当尝试将 POCO 映射到 record 时,嵌套 属性 失败.

请看下面代码:

using AutoMapper;
using FluentAssertions;
using NUnit.Framework;

// All the following stuff is necessary to be used with EF Core
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Local
// ReSharper disable UnusedMember.Global
#pragma warning disable 8618

namespace Tests.UnitTests
{
    [TestFixture]
    public class MyTests
    {
        [Test]
        public void MappingTest()
        {
            var book = new Book(new Person("Oscar"));
            var mapper = new MapperConfiguration(x => x.AddProfile<AutoMapperProfile>()).CreateMapper();

            var result = mapper.Map<Book, ExistingBook>(book);

            result.CreatedBy.Should().Be(book.CreatedBy.Name);
        }
    }

    public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile() => CreateMap<Book, ExistingBook>().ForMember(x => x.CreatedBy, y => y.MapFrom(z => z.CreatedBy.Name));
    }

    public record ExistingBook(string CreatedBy);

    public class Person
    {
        public Person()
        {
        }

        public Person(string name) => Name = name;

        public string Name { get; private set; }
    }

    public class Book
    {
        public Book()
        {
        }

        public Book(Person createdBy) => CreatedBy = createdBy;

        public Person CreatedBy { get; private set; }
    }
}

执行 MappingTest() 时失败 Expected result.CreatedBy to be "Oscar" with a length of 5, but "Tests.UnitTests.Person" has a length of 22, differs near "Tes" (index 0).

我是不是做错了什么或者这是一个错误?

您在这里通过构造函数进行映射。所以你需要 ForCtorParam.

CreateMap<Book, ExistingBook>().ForCtorParam(nameof(ExistingBook.CreatedBy), options => options.MapFrom(book => book.CreatedBy.Name));