【发布时间】:2021-08-29 04:29:35
【问题描述】:
我将 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。 -
啊太好了-谢谢!您想发布您的解决方案作为答案吗?
-
顺便说一句:根据我的经验,删除自动映射器并在记录中使用
FromXy()函数会更简单。如果您的记录需要所有数据作为 ctor 参数,编译器将确保一切正常,因此在大多数情况下无需添加测试。最后,我们大多数项目中的代码都更少了) -
@ChristophLütjen 你的意思是你要创建一个方法
ExistingBook.FromBook()并手动进行映射? -
没错。如果您的 ctor 需要所有属性作为参数(如您的示例中所示),编译器将确保所有属性都已映射。
标签: c# automapper