完整来源;
// 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
{
}
我可以通过从Entity
中删除public ApplicationUser CreatedBy { get; set; }
或从EntityDto
中删除public DateTime Created { get; set; }
来使代码工作。
版本:
这只发生在使用AutoMapper 11.0.1的。net 7中。它将与。net 7(使用AutoMapper 12.0.0)或。net 6(使用AutoMapper 11.0.1)一起工作。鉴于我们的项目依赖于NuGet https://www.nuget.org/packages/Microsoft.AspNetCore.ApiAuthorization.IdentityServer/7.0.0#dependencies-body-tab (Blazor默认的NuGet,当一个项目是从Visual Studio与个人用户帐户创建的),反过来使用https://www.nuget.org/packages/Duende.IdentityServer.EntityFramework.Storage/6.0.4#dependencies-body-tab,我不能升级到AutoMapper 12.0.0,因为依赖有AutoMapper (>= 11.0.0 &&;& lt;12.0.0)
我曾经尝试过手动升级Duende.Identity
Nugets,因为有时会有问题,但通常有些事情最终会与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'.
找到答案了。在发布之前搜索了问题,但我搜索了完整的例外,一无所获。
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());
});
依赖注入:
services.AddAutoMapper(cfg => cfg.Internal().MethodMappingEnabled = false, typeof(MappingProfile).Assembly);