Error mapping types

User-1355965324 posted

User-1355965324 posted

When I am mapping using mapper  between the model the error is being showed AutoMapper.AutoMapperMappingException: ‘Error mapping types.’

I have the following model

  public class Country
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [Required]
        [MaxLength(50, ErrorMessage = "Country must be up to 50 characters in length")]
        public string CountryName { get; set; }
       public  ICollection<Author> Authors { get; set; }
    }


 public class CountryDto
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
        public  ICollection<AuthorDto> Authors { get; set; }
    }

public class Author
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Required]
        [MaxLength(100, ErrorMessage ="First Name cannot be more than 100 characters")]
        public string FirstName { get; set; }

        [Required]
        [MaxLength(200, ErrorMessage = "Last Name cannot be more than 200 characters")]
        public string LastName { get; set; }
        public  Country Country { get; set; }
        [NotMapped]
        public  ICollection<BookAuthor> BookAuthors { get; set; }
    }

    public class AuthorDto
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

startup.cs
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<BookStoreDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllers();
            services.AddScoped<ICountryRepository, CountryRepository>();           
            services.AddAutoMapper(typeof(Mapping));
        }

API Controller
 public IActionResult GetCountries()
        {
            var objList = _countryRepository.GetCountries();
            var mappedEntities = _mapper.Map<CountryDto[]>(objList);

            

            if (!ModelState.IsValid)
                return BadRequest(ModelState);

           

            return Ok(mappedEntities);
        }

Repository class

 public Country[] GetCountries()
        {
           // return _db.Countries.Include(a=> a.Authors).OrderBy(c => c.CountryName).ToList();
            IQueryable<Country> query = _db.Countries
                                   .Include(a => a.Authors);
 

            

            return  query.ToArray();
        }

Mapping.cs

 public class Mapping : Profile
    {
        public Mapping()
        {
            CreateMap<Country, CountryDto>()
                .ReverseMap()
                 .ForMember(a => a.Authors, a => a.Ignore()); 
           
        }
    }

Record is as follows

Country table
CountryId        CountryName
1                  UK
2                   US
3                  China
4                  India
5                  Canada

Author
Id                FirstName   LastName                  CountryID
 1                 Test        Author                     1
 2                 Reena       Tom                        2

When I map   the error is coming is as follows

AutoMapper.AutoMapperMappingException: ‘Error mapping types.’

**Hi
i try to insert data from «AZTRH» table in my database to same table but in another database — i do the following:

  1. i get data from my database and add it to session
  2. create list that will be get all items in session .
  3. try do mapping as code:**
            var config = new MapperConfiguration(cfg => cfg.CreateMap<AZTRHExpire, AZTRHNoraml>());
            var mapper = config.CreateMapper();

                                foreach (var i in _listtomove)
                                {
                                    var thing = new Models.azDbContext.AZTRHNormal();

                                    mapper.Map(i, thing);

                                    int newid;

                                    if (!datatoadd.AZTRHs.Any())
                                    {
                                        newid = 1;
                                    }
                                    else
                                    {
                                        newid = datatoadd.AZTRHs.Max(o => o.TR_NO) + 1;
                                    }

                                    thing.TR_NO = newid;
                                    datatoadd.AZTRHs.Add(thing);
                                }

                                datatoadd.SaveChanges();

                                return Ok(new { success = true, message = "تم نقل الإذون بنجاح" });

but i got error in this line

mapper.Map(i, thing);

i got error:

Error mapping types.

Mapping types:
AZTRHExpire -> AZTRHNoraml
PricingUpdate.Models.ExpireDbContext.AZTRHExpire > PricingUpdate.Models.azDbContext.AZTRHNoraml

Type Map configuration:
AZTRHExpire -> AZTRHNoraml
PricingUpdate.Models.ExpireDbContext.AZTRHExpire > PricingUpdate.Models.azDbContext.AZTRHNoraml

Property:
AZTRDs

the table «aztrd» has relation with table aztrh in doth databases but i don’t use it here yet i will use it too

and when i add this code:

mapper.ConfigurationProvider.AssertConfigurationIsValid();

i got error details as:

The following property on PricingUpdate.Models.azDbContext.AZTRDNoraml cannot be mapped:

Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type > PricingUpdate.Models.azDbContext.AZTRDNoraml.
Context:
Mapping from type PricingUpdate.Models.ExpireDbContext.AZTRDExpire to > PricingUpdate.Models.azDbContext.AZTRDNoraml
Exception of type ‘AutoMapper.AutoMapperConfigurationException’ was thrown.

so please what is problem here and how can i resolve it … ??!!

I am getting a peculiar error with Automapper

Error messages:

Mapping types:
TransportOffer -> TransportOfferDto
Model.TransportOffer -> Dto.TransportOfferDto

Type Map configuration:
TransportOffer -> TransportOfferDto
Model.TransportOffer -> Dto.TransportOfferDto

Property:
FromCity ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
City -> CityDto
Model.City -> Dto.CityDto

Type Map configuration:
City -> CityDto
Model.City -> Dto.CityDto

Property:
Country ---> System.TypeLoadException: Method 'Add' in type 'Proxy_System.Collections.Generic.ICollection`1[[Dto.CountryDto, BusinessLogic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]__17474517' from assembly 'AutoMapper.Proxies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005' does not have an implementation.

Below are my entities and DTO and the query that retrieves the data.
I am using Automapper 7.0.1 and Automapper.Attributes 6.0.1

I have tried also with custom mapping configuration and the error is the same.

Here is the Automapper custom property configuration:

Mapper.Initialize
(
    config =>
    {
        config.CreateMap<TransportOfferDto, TransportOffer>()
            .ForMember(dest => dest.FromCity, conf => conf.MapFrom(src => src.FromCity))
            .ForMember(dest => dest.FromCountry, conf => conf.MapFrom(src => src.FromCountry))
            .ForMember(dest => dest.ToCity, conf => conf.MapFrom(src => src.ToCity))
            .ForMember(dest => dest.ToCountry, conf => conf.MapFrom(src => src.ToCountry));
         }
     );

Country — entity:

public class Country : BaseEntity<Int32>
{        
    public string Name { get; set; }
    public string Code { get; set; }
    public string Capital { get; set; }
    public Int32 TotalSold { get; set; }
}

CountryDto

[MapsTo(typeof(Country))]
[MapsFrom(typeof(Country))]
public class CountryDto : EntityDto<Int32>
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string Capital { get; set; }
    public Int32 TotalSold { get; set; }
}

City — entity:

public class City : BaseEntity<Int32>
{        
    public string Name { get; set; }
    public Int32 CountryID { get; set; }
    public virtual Country Country { get; set; }
}

CityDto

[MapsTo(typeof(City))]
[MapsFrom(typeof(City))]
public class CityDto : EntityDto<Int32>
{
    public Int32 CountryID { get; set; }
    public virtual ICollection<CountryDto> Country { get; set; }

    public string Name { get; set; }

}

TransportOffer — entity:

public class TransportOffer : BaseEntity<Guid>
{
    public Guid TransportToken { get; set; }
    public DateTime Date { get; set; }
    public Int32 FromCityID { get; set; }
    public  virtual City FromCity { get; set; }
    public Int32 FromCountryID { get; set; }
    public virtual Country FromCountry { get; set; }
    public Int32 ToCityID { get; set; }
    public virtual City ToCity { get; set; }
    public Int32 ToCountryID { get; set; }
    public virtual Country ToCountry { get; set; }
}

TransportOfferDto:

[MapsTo(typeof(TransportOffer))]
[MapsFrom(typeof(TransportOffer))]
public class TransportOfferDto : EntityDto<Guid>
{
    public Guid TransportToken { get; set; }
    public DateTime Date { get; set; }    
    public Int32 FromCityID { get; set; }
    public virtual CityDto FromCity { get; set; }       
    public Int32 FromCountryID { get; set; }
    public virtual CountryDto FromCountry { get; set; } 
    public Int32 ToCityID { get; set; }
    public virtual CityDto ToCity { get; set; }
    public Int32 ToCountryID { get; set; }
    public virtual Country ToCountry { get; set; }
} 

Query

var query = Repository.GetAll()
            .Include(x => x.FromCountry)
            .Include(x => x.FromCity)
            .Include(x => x.ToCountry)
            .Include(x => x.ToCity)
            .Where(p => p.MembershipID == input).ToList();

return ObjectMapper.Map<List<TransportOfferDto>>(query);

Содержание

  1. Nullable properties mapping failure #2123
  2. Comments
  3. Source/destination types
  4. Mapping configuration
  5. Version: 6.0.2
  6. Expected behavior
  7. Actual behavior
  8. Steps to reproduce
  9. Footer
  10. Custom Value Resolvers¶
  11. Custom constructor methods¶
  12. The resolved value is mapped to the destination property¶
  13. Customizing the source value supplied to the resolver¶
  14. Passing in key-value to Mapper¶
  15. ForPath¶
  16. Resolvers and conditions¶

Nullable properties mapping failure #2123

Source/destination types

Mapping configuration

Version: 6.0.2

Expected behavior

Mapper.AssertConfigurationIsValid(); does not complain, so I would expect that mapping from/to Nullable<> versions of configured types would work (if those properties are not nullable, it works).

Actual behavior

following exception is thrown:

Steps to reproduce

I’m positive that this used to work in old version of Automapper (3.3.1 to be exact)

The text was updated successfully, but these errors were encountered:

Now it complains 🙂 Try the MyGet build. So now you need:

confirming that AutoMapper 6.1.0-ci-01328 is throving exception now on Mapper.AssertConfigurationIsValid() , but is this necessary?
If we have a mapping configured between T and U , why do we need to explicitly configure also mapping for their Nullable<> versions? we don’t need to explicitly define mapping for int -> int?
I see only 4 cases here:
T -> U => this is normal case, use map T->U
T -> U? => always safe, use map T->U
T? -> U? => safe, If T null destination is also null, otherwise use map T->U
T? -> U => can be dangerous (if T is null), complain in AssertConfigurationIsValid()

I see in #1987 that there was some attempt to consolidate this

A PR is welcome.

Hi every one
I have a strange problem in my web App. I used Mapper for mapped class to each other, But sometimes I get a error and after IIS stop and start every thing work fine.
this happens cause of GetVersionID that refers to primary key in GetVersion property that is NotNull.
I use code like that :
Mapper.CreateMap ();

Can somebody help me .

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Custom Value Resolvers¶

Although AutoMapper covers quite a few destination member mapping scenarios, there are the 1 to 5% of destination values that need a little help in resolving. Many times, this custom value resolution logic is domain logic that can go straight on our domain. However, if this logic pertains only to the mapping operation, it would clutter our source types with unnecessary behavior. In these cases, AutoMapper allows for configuring custom value resolvers for destination members. For example, we might want to have a calculated value just during mapping:

For whatever reason, we want Total to be the sum of the source Value properties. For some other reason, we can’t or shouldn’t put this logic on our Source type. To supply a custom value resolver, we’ll need to first create a type that implements IValueResolver:

The ResolutionContext contains all of the contextual information for the current resolution operation, such as source type, destination type, source value and so on. An example implementation:

Once we have our IValueResolver implementation, we’ll need to tell AutoMapper to use this custom value resolver when resolving a specific destination member. We have several options in telling AutoMapper a custom value resolver to use, including:

  • MapFrom
  • MapFrom(typeof(CustomValueResolver))
  • MapFrom(aValueResolverInstance)

In the below example, we’ll use the first option, telling AutoMapper the custom resolver type through generics:

Although the destination member (Total) did not have any matching source member, specifying a custom resolver made the configuration valid, as the resolver is now responsible for supplying a value for the destination member.

If we don’t care about the source/destination types in our value resolver, or want to reuse them across maps, we can just use “object” as the source/destination types:

Custom constructor methods¶

Because we only supplied the type of the custom resolver to AutoMapper, the mapping engine will use reflection to create an instance of the value resolver.

If we don’t want AutoMapper to use reflection to create the instance, we can supply it directly:

AutoMapper will use that specific object, helpful in scenarios where the resolver might have constructor arguments or need to be constructed by an IoC container.

The resolved value is mapped to the destination property¶

Note that the value you return from your resolver is not simply assigned to the destination property. Any map that applies will be used and the result of that mapping will be the final destination property value. Check the execution plan.

Customizing the source value supplied to the resolver¶

By default, AutoMapper passes the source object to the resolver. This limits the reusability of resolvers, since the resolver is coupled to the source type. If, however, we supply a common resolver across multiple types, we configure AutoMapper to redirect the source value supplied to the resolver, and also use a different resolver interface so that our resolver can get use of the source/destination members:

Passing in key-value to Mapper¶

When calling map you can pass in extra objects by using key-value and using a custom resolver to get the object from context.

This is how to setup the mapping for this custom resolver

ForPath¶

Similar to ForMember, from 6.1.0 there is ForPath. Check out the tests for examples.

Resolvers and conditions¶

For each property mapping, AutoMapper attempts to resolve the destination value before evaluating the condition. So it needs to be able to do that without throwing an exception even if the condition will prevent the resulting value from being used.

As an example, here’s sample output from BuildExecutionPlan (displayed using ReadableExpressions) for a single property:

The default generated code for resolving a property, if you haven’t customized the mapping for that member, generally doesn’t have any problems. But if you’re using custom code to map the property that will crash if the condition isn’t met, the mapping will fail despite the condition.

This example code would fail:

The condition prevents the Value property from being mapped onto the target, but the custom member mapping would fail before that point because it calls Value.Length, and Value is null.

Prevent this by using a PreCondition instead or by ensuring the custom member mapping code can complete safely regardless of conditions:

Источник

I have the following error when using Automapper:

Error mapping types

Mapping types:

Order -> OrderResp

DB.Entities.Order -> Application.Orders.Models.OrderResp

Destination Member:

OrderItems

—> Automapper.AutomapperMappingException: Error mapping types.

These are my Automapper profiles:

public class OrderProfile : Profile 
{    
   public OrderProfile()    
     {       
        CreateMap<Order, OrderDTO>();       
        CreateMap<Order, OrderResp>();    
     } 
}   


public class OrderItemProfile : Profile 
{    
   public OrderItemProfile()    
     {        
         CreateMap<OrderItem, Domain.Models.OrderItem>();   
     }
}

These are my classes:

public class OrderResp // Application.Orders.Models 
{     
   public List<OrderItem> OrderItems { get; set; } 
} 
 
 
public class Order // DB.Entities 
{     
   [Key]     
   public int Id { get; set; }     
   public List<OrderItem> OrderItems { get; set; } 
}   


public class Order // Domain.Models 
{    
   public int Id { get; set; }    
   public List<OrderItem> OrderItems { get; set; }
}

Here I use Automapper:

var order = await _context.Orders                   
   .Include(x => x.OrderItems)
       .SingleOrDefaultAsync(p => p.Id == request.Id,
               cancellationToken: cancellationToken);  

return _mapper.Map<OrderResp>(order);

I have tried to use CreateMap<List<OrderItem>, List<Domain.Models.OrderItem>>() in OrderItemProfile and I don’t get the error anymore but my List is empty.

How can I make this work?

Anvean

63 / 55 / 10

Регистрация: 12.02.2019

Сообщений: 303

1

21.05.2021, 18:45. Показов 3805. Ответов 2

Метки нет (Все метки)


Сущности

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

C#
1
2
3
4
5
6
7
 public class CourseVM : BasicVM
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public ICollection<SkillVM> Skills { get; set; }
        public ICollection<MaterialVM> Materials { get; set; }
    }

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

C#
1
2
3
4
5
6
7
 public class Course : BasicEntity
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public ICollection<Skill> Skills { get; set; }
        public ICollection<Material> Materials { get; set; }
    }

Соответственно VM и Domain.
Метод маппера —

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

C#
1
2
3
4
5
6
7
8
 public static Course CourseVmToDomain(CourseVM courseVM)
        {
            var configuration = new MapperConfiguration(cfg => cfg.CreateMap<CourseVM, Course>()
            .ForMember(dest => dest.Skills, opt => opt.MapFrom(src => src.Skills))
            .ForMember(dest => dest.Materials, opt => opt.MapFrom(src => src.Materials)));
            var mapper = new Mapper(configuration);
            return mapper.Map<CourseVM, Course>(courseVM);
        }

Вот так выглядит ошибка
AutoMapper.AutoMapperMappingException: ‘Error mapping types.’
Inner ex.
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Вопрос как правильно мапить вложенные коллекции? Прочитал уже много всего и попробовал тоже. Проект — консольный .net core.
Помогите пожалуйста :)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



escoult

1518 / 443 / 125

Регистрация: 09.01.2018

Сообщений: 1,025

21.05.2021, 19:54

2

Лучший ответ Сообщение было отмечено Anvean как решение

Решение

Так у вас нет конфигурации маппинга Skill и Material.
Добавьте, будет маппить:

C#
1
2
3
4
5
6
7
8
9
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Course, CourseVM>();
                cfg.CreateMap<CourseVM, Course>();
                cfg.CreateMap<Skill, SkillVM>();
                cfg.CreateMap<SkillVM, Skill>();
                cfg.CreateMap<Material, MaterialVM>();
                cfg.CreateMap<MaterialVM, Material>();
            });



1



63 / 55 / 10

Регистрация: 12.02.2019

Сообщений: 303

21.05.2021, 20:10

 [ТС]

3

escoult, Спасибо вам большое, всё гениальное всегда просто:)



0



Posted By: Anonymous

Using AutoMapper, I tried to display the list of the posts with comments array in the result. However, as a newbie of AutoMapper, I faced an issue with unnecessary information in the comments array shown. I tried to use CommentDTO in PostDTO but when using it, it occurs an error of mapping type. Instead, I added another CreateMap<Comment, CommentDto>, but it doesn’t work inside PostDTO. Can you let me know how to deal with this issue?

Models

// post
   public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int EmployeeId { get; set; }
        public Employee Employee { get; set; }

        public IList<Comment> Comments { get; set; }
    }

// Comment
 public class Comment
    {
        [Key]
        public int Id { get; set; }
        public string text { get; set; }
        public int EmployeeId { get; set; }
        public int PostId { get; set; }

        public virtual Employee Employee { get; set; }
        public virtual Post Post { get; set; }
    }

DTO

// PostDTO
public class PostDTO
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string OrgName { get; set; }

        [JsonPropertyName("comments")]
        public IList<Comment> Comments { get; set; }  
        // When using 'public IList<CommentDTO> Comments { get; set; }' it occurs an error.
    }

// CommentDTO
 public class CommentDTO
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public int CommentAuthor { get; set; }
    }

MappingProfile

 public class MappingProfile : AutoMapper.Profile
    {
        public MappingProfile()
        {

            CreateMap<Organization, OrgDTO>();
            CreateMap<Employee, EmpDTO>()
                .ForMember(d => d.OrgName, o => o.MapFrom(e => e.Organization.Name))
                .ForMember(d => d.Name, o => o.MapFrom(e => e.Name))
                .ForMember(d => d.Posts, o => o.MapFrom(e => e.Posts));

            CreateMap<Comment, CommentDTO>()
                .ForMember(d => d.CommentAuthor, o => o.MapFrom(c => c.Employee.Name))
                .ForMember(d => d.Text, o=>o.MapFrom(c =>c.text));

            CreateMap<Post, PostDTO>()
                .ForMember(d => d.Author, o => o.MapFrom(p => p.Employee.Name))
                .ForMember(d => d.OrgName, o => o.MapFrom(p => p.Employee.Organization.Name));
        }
    }

Services

public List<PostDTO> GetAllPosts()
        {
            var posts = _context.Posts
                .Include(x => x.Employee)
                .ThenInclude(x => x.Organization)
                .Include(x =>x.Comments)
                .ToList();
            List<PostDTO> result = _mapper.Map<List<Post>, List<PostDTO>>(posts);

            return result;
        }

Actual Result

[
  {
    "id": 1,
    "title": "Test1",
    "author": "Tom",
    "orgName": "A",
    "comments": [
      {
        "id": 1,
        "text": "Good",
        "employeeId": 1,
        "postId": 1,
        "employee": {
          "id": 1,
          "name": "Tom",
          "organizationId": 1,
          "organization": {
            "id": 1,
            "name": "A",
            "employees": [
              {
                "id": 2,
                "name": "Kevin",
                "organizationId": 1,
                "posts": [
                  {
                    "id": 4,
                    "title": "Test4",
                    "employeeId": 2,
                    "comments": []
                  }
                ],
                "comments": [
                  {
                    "id": 2,
                    "text": "Bad",
                    "employeeId": 2,
                    "postId": 1,
                    "post": {
                      "id": 1,
                      "title": "Test1",
                      "employeeId": 1,
                      "comments": []
                    }
                  }
                ]
              }
            ]
          },
          "posts": [
            {
              "id": 1,
              "title": "Test1",
              "employeeId": 1,
              "comments": [
                {
                  "id": 2,
                  "text": "Bad",
                  "employeeId": 2,
                  "postId": 1,
                  "employee": {
                    "id": 2,
                    "name": "Kevin",
                    "organizationId": 1,
                    "organization": {
                      "id": 1,
                      "name": "A",
                      "employees": []
                    },
                    "posts": [
                      {
                        "id": 4,
                        "title": "Test4",
                        "employeeId": 2,
                        "comments": []
                      }
                    ],
                    "comments": []
                  }
                }
              ]
            .....

Expected Result

[
  {
    "id": 1,
    "title": "Test1",
    "author": "Tom",
    "orgName": "A",
    "comments": [
      {
       "id": 1,
       "Text": "Nicee",
       "CommentAuthor": "Kevin"
      },
    ]
   },
...

Error

AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
List`1 -> List`1
System.Collections.Generic.List`1[[Persistence.Models.Post, Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.List`1[[Application.DTO.PostDTO, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Post -> PostDTO
Persistence.Models.Post -> Application.DTO.PostDTO

Type Map configuration:
Post -> PostDTO
Persistence.Models.Post -> Application.DTO.PostDTO

Destination Member:
Comments

 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
IList`1 -> IList`1
System.Collections.Generic.IList`1[[Persistence.Models.Comment, Persistence, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IList`1[[Application.DTO.CommentDTO, Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Comment -> CommentDTO
Persistence.Models.Comment -> Application.DTO.CommentDTO

Type Map configuration:
Comment -> CommentDTO
Persistence.Models.Comment -> Application.DTO.CommentDTO

Destination Member:
CommentAuthor

 ---> System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , IList`1 , IList`1 , ResolutionContext )
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   --- End of inner exception stack trace ---
   at lambda_method(Closure , List`1 , List`1 , ResolutionContext )
   at Application.Services.GetAllPosts() in C:UserssbaekDocumentsDev.NET Core LINQ_210605210605ApplicationServices.cs:line 32
   at WebAPI.Controllers.BlogController.GetAllPost() in C:UserssbaekDocumentsDev.NET Core LINQ_210605210605WebAPIControllersBlogController.cs:line 26
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context)
   at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)


Solution

Your CommentDTO has a property int CommentAuthor which is mapped from Employee.Name, which I assume is a string. It sounds like you need to make CommentAuthor a string.

Answered By: Anonymous

Related Articles

  • Automapper Aftermap alternative for Nested Mapping
  • Reference — What does this regex mean?
  • Callback functions in C++
  • Nested routes in Ember JS and Ember Rails
  • How to filter a RecyclerView with a SearchView
  • Automapper missing type map configuration or unsupported…
  • How to map lists without overwriting values
  • Ember Data. Save model with «belongsTo» relationship
  • Django Blog — Comment System
  • How to fix filter by column in angular?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Понравилась статья? Поделить с друзьями:
  • Error manifest merger failed with multiple errors see logs
  • Error management culture
  • Error man minecraft
  • Error malformed utf 8 string
  • Error malformed utf 8 data