AutoMapper.AutoMapperMappingException: тип 'System.String' не имеет конструктора по умолчанию - PullRequest
5 голосов
/ 06 июня 2011

Странная ошибка стала появляться в нашем коде в последнюю неделю или две. Я пытаюсь определить основную причину сбоя сопоставления. Самое внутреннее исключение вызывает недоумение: Type 'System.String' does not have a default constructor

Я не понимаю, что говорит мне исключение. Можете ли вы объяснить, что произошло, и, возможно, как я мог решить эту ошибку?

Картограф используется в универсальном методе:

public TEntity UpdateWithHistory<TEntity>(TEntity entity, int? entityID, int? interviewID)
where TEntity : class
{
    var snapshot = _interviewContext.Find<TEntity>(entityID);

    // This is call that fails
    var history = Mapper.Map<TEntity, TEntity>(snapshot);

    _interviewHistory.Set<TEntity>().Add(history);
    MarkModified(entity);
    return Mapper.Map(entity, snapshot);
}

В приведенном выше коде снимок НЕ является нулевым. Полное исключение:

AutoMapper.AutoMapperMappingException:
Trying to map Recog.Web.Models.InterviewComment to Recog.Web.Models.InterviewComment.
Using mapping configuration for Recog.Web.Models.InterviewComment to Recog.Web.Models.InterviewComment
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
  ---> AutoMapper.AutoMapperMappingException: Trying to map System.String to System.String.
       Using mapping configuration for System.String to System.String
       Destination property: Comment
       Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
  ---> AutoMapper.AutoMapperMappingException: Trying to map System.String to System.String.
       Using mapping configuration for System.String to System.String
       Destination property: Comment
       Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
  ---> System.ArgumentException: Type 'System.String' does not have a default constructor
     at System.Linq.Expressions.Expression.New(Type type)
     at AutoMapper.DelegateFactory.CreateCtor(Type type)
     at AutoMapper.Mappers.ObjectCreator.CreateObject(Type type)
     at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.CreateObject(ResolutionContext context)
     at AutoMapper.Mappers.TypeMapObjectMapperRegistry.NewObjectPropertyMapMappingStrategy.GetMappedObject(ResolutionContext context, IMappingEngineRunner mapper)
     at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
     at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
     at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
     --- End of inner exception stack trace ---
     at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
     at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
     --- End

Класс Comment, который упоминается:

public class InterviewComment
{
    [Key]
    public int? InterviewCommentID { get; set; }

    [ForeignKey("Interview")]
    public int? InterviewID { get; set; }

    [CodeType(CodeTypeEnum.CommentSection)]
    public int? CommentSectionCodeID { get; set; }

    [CodeType(CodeTypeEnum.CommentSource)]
    public int? CommentSourceCodeID { get; set; }

    [Display(Name = "Comment")]
    [StringLength(int.MaxValue)]
    public string Comment { get; set; }

    [Include]
    [Association("Interview_1-*_InterviewComment", "InterviewID", "InterviewID", IsForeignKey = true)]
    public virtual Interview Interview { get; set; }

    [ReadOnly(true)]
    [ForeignKey("ModifiedByUser")]
    public virtual ApplicationUser ApplicationUser { get; set; }

    [ReadOnly(true)]
    public string UserName
    {
        get { return ApplicationUser != null ? ApplicationUser.GetDisplayName() : null; }
    }

    [ReadOnly(true)]
    public int CreatedByUser { get; set; }

    [ReadOnly(true)]
    public DateTime CreatedDateTime { get; set; }

    [ReadOnly(true)]
    public int ModifiedByUser { get; set; }

    [ReadOnly(true)]
    public DateTime ModifiedDateTime { get; set; }
}

Я все еще проверяю последние коммиты, чтобы определить изменение, которое вызывает это. Любое понимание этого исключения будет с благодарностью.

Ответы [ 3 ]

6 голосов
/ 15 июня 2011

Основная причина ошибки была в коде, который не был передан.У нас есть соглашение, которое настраивает отображения для определенных типов, обнаруженных с помощью отражения.Наш алгоритм неправильно создал карту для string, заменив сопоставление по умолчанию, предоставляемое AutoMapper.

Если вы когда-нибудь увидите ошибку Type 'System.String' does not have a default constructor, убедитесь, что ваш код не создает карту для string.

2 голосов
/ 22 июня 2012

У меня была такая же ошибка.Я хотел отобразить массив объектов на массив объектов

Эта сгенерированная ошибка

AutoMapper.AutoMapperMappingException: Тип 'TargetObjectType'

не имеетконструктор по умолчанию:

AutoMapper.Mapper.CreateMap<SourceObjectType[], TargetObjectType[]>();
TargetObject = AutoMapper.Mapper.Map<SourceObjectType[], TargetObjectType[]>(SourceObject);

Когда я правильно установил типы для отображения, ошибка исчезла.

AutoMapper.Mapper.CreateMap<SourceObjectType, TargetObjectType>();
2 голосов
/ 06 июня 2011

Строка не имеет конструктора по умолчанию, который в любом случае не будет полезен, так как строка является неизменной.

Чтобы сузить проблему, какие данные передаются в метод.Какие данные вы пытаетесь отобразить.Каково значение свойства Comment в элементе, который вы пытаетесь сопоставить?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...