'T MaxInteger[T](System.Collections.Generic.IEnumerable`1[T])' 上的 System.DateTime 违反了使用 AutoMapper 11.0.1 的 .NET 7 类型 T 的约束

Ogg*_*las 24 .net c# automapper nuget automapper-11

完整源码;

// See https://aka.ms/new-console-template for more information
using AutoMapper;

Console.WriteLine("Hello, World!");

var mapperConfig = new MapperConfiguration(mc =>
{
    mc.AddProfile(new MappingProfile());
});
//mapperConfig.AssertConfigurationIsValid();

IMapper mapper = mapperConfig.CreateMapper();

var entity = new Entity() { Created = DateTime.Now };

var entityDto = mapper.Map<Entity, EntityDto>(entity);

Console.WriteLine("Test");

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Entity, EntityDto>().ReverseMap();
    }
}

public class Entity
{
    public Guid Guid { get; set; }

    public DateTime Created { get; set; }

    public string CreatedById { get; set; }

    public ApplicationUser CreatedBy { get; set; }

}

public class EntityDto
{
    public Guid Guid { get; set; }

    public DateTime Created { get; set; }

    public string CreatedById { get; set; }

}

public class ApplicationUser
{

}
Run Code Online (Sandbox Code Playgroud)

public ApplicationUser CreatedBy { get; set; }我可以通过删除Entity或删除public DateTime Created { get; set; }来使代码工作EntityDto

版本:

这种情况仅发生在使用 AutoMapper 11.0.1 的 .NET 7 中。它将使用 AutoMapper 12.0.0 与 .NET 7 配合使用,或使用 AutoMapper 11.0.1 与 .NET 6 配合使用。鉴于我们的项目依赖于 NuGet https://www.nuget.org/packages/Microsoft.AspNetCore.ApiAuthorization.IdentityServer/7.0.0#dependency-body-tab(当从 Visual Studio 创建项目时,Blazor 默认 NuGet个人用户帐户),依次使用https://www.nuget.org/packages/Duende.IdentityServer.EntityFramework.Storage/6.0.4#dependency-body-tab我无法升级到 AutoMapper 12.0.0,因为存在依赖关系是AutoMapper (>= 11.0.0 && < 12.0.0)

我之前曾尝试Duende.Identity手动升级 Nuget,因为时不时会出现问题,但通常会出现问题,Microsoft.AspNetCore.ApiAuthorization.IdentityServer所以我宁愿不这样做。例子:

https://github.com/dotnet/aspnetcore/issues/41897

例外

System.ArgumentException: 'GenericArguments[0], 'System.DateTime', on 'T MaxInteger[T](System.Collections.Generic.IEnumerable`1[T])' violates the constraint of type 'T'.'

Inner Exception
VerificationException: Method System.Linq.Enumerable.MaxInteger: type argument 'System.DateTime' violates the constraint of type parameter 'T'.
Run Code Online (Sandbox Code Playgroud)

Ogg*_*las 20

找到了答案。在发布之前搜索了问题,但我搜索了完整的异常,但什么也没找到。

https://github.com/AutoMapper/AutoMapper/issues/3988#issuecomment-1140716814

using AutoMapper;
using AutoMapper.Internal;

var mapperConfig = new MapperConfiguration(mc =>
{
    mc.Internal().MethodMappingEnabled = false;
    mc.AddProfile(new MappingProfile());
});
Run Code Online (Sandbox Code Playgroud)

依赖注入:

services.AddAutoMapper(cfg => cfg.Internal().MethodMappingEnabled = false, typeof(MappingProfile).Assembly);
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,就我而言,这也实现了“config.ShouldMapMethod = (m =&gt; false);”的技巧 (11认同)