Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c# - automapper usage returning "Unable to cast object of type 'WebAPIs.Models.Store' to type 'WebAPIs.ValueModels.StoreVM'"

I'm new to AutoMapper and I mapped a model to a view-model to output specific data. Although the data are being registered and being outputted correctly, I am getting the following error, sorry for the bother and if you need any more information I would happily oblige you

System.InvalidCastException: Unable to cast object of type 'WebAPIs.Models.Store' to type 'WebAPIs.ValueModels.StoreVM'. at WebAPIs.Controllers.CRUDController`2.Create(CreateOrUpdateRecord request) in C:UsersUSERsourceReposWebAPIsWebAPIsControllersCRUDController.cs:line 65 at lambda_method(Closure , Object ) at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()

This is my controller -

[HttpPost]
[ProducesResponseType(typeof(Store), 201)]
public Task<ActionResult<StoreVM>> Create([FromBody] CreateOrUpdateStore request)
{
    return base.Create(request);
}

which extends this -

protected async Task<ActionResult<TValueModel>> Create(CreateOrUpdateRecord request)
{
    request.Id = null;
    var response = await _mediator.Send(request);
    if (!response.IsSuccess)
    {
        return BadRequest(
            new
            {
                response.Error
            });
    }

    var record = (TValueModel)response.Result!;
    return CreatedAtAction(
        nameof(GetById), new { id = record.Id }, record);
}

The AutoMapper configuration -

public static class ModelViewMapper
{
    private static readonly Lazy<IMapper> mapper = new Lazy<IMapper>(() =>
    {
        var config = new MapperConfiguration((cfg) =>
        {
            cfg.CreateMap<CreateOrUpdateStore, Store>();

            cfg.CreateMap<Store, StoreVM>().ReverseMap();
            cfg.CreateMap<User, UserVM>().ReverseMap();
            cfg.CreateMap<Product, ProductVM>().ReverseMap();
            cfg.CreateMap<Category, CategoryVM>().ReverseMap();

        });
        var mapper = config.CreateMapper();
        return mapper;
    });

    public static IMapper Mapper => mapper.Value;
}

The store model -

public class Store : BaseModel
{
    public string Name { get; set; } = null!;
    //public List<Product> Products { get; set; } = new List<Product>();
    public string City { get; set; } = null!;
    public string Address { get; set; } = null!;
    //public List<Category> Types { get; set; } = null! ;

    [ForeignKey(nameof(Owner))]
    public Guid? OwnerId { get; set; }
    public User? Owner { get; set; }
    public string Description { get; set; } = null!;
    public string Details { get; set; } = null!;
    public string Logo { get; set; } = null!;
}

The value model -

public class StoreVM : BaseValueModel
{
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public string Details { get; set; } = string.Empty;
    public string Logo { get; set; } = string.Empty;

    //public List<ProductVM> Products { get; set; } = new List<ProductVM>();

}

CrudHandler -
(most generic post-operation will extend this handler handler)

private async Task<ICommandResult> Create(CreateOrUpdateRecord request, CancellationToken cancellationToken)
{
    var record = ModelViewMapper.Mapper.Map<TModel>(request);
    record.Id = Guid.NewGuid();
    record.CreatedAt = record.UpdatedAt = DateTime.UtcNow;

    DbSet.Add(record);
    await _dbContext.SaveChangesAsync(cancellationToken);

    return new CommandResult
    {
        Result = record
    };
}
question from:https://stackoverflow.com/questions/66060676/automapper-usage-returning-unable-to-cast-object-of-type-webapis-models-store

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not mapping the your Store to StoreVM before returning it to the controller.

In your Create crud-handler method, modify the return statement from -

return new CommandResult
{
    Result = record
};

to -

return new CommandResult
{
    Result = ModelViewMapper.Mapper.Map<StoreVM>(record);
};

Not directly related to your issue :
With ASP.NET Core applications, you are supposed to register AutoMapper and create an IMapper instance through dependency injection. For further detail - https://docs.automapper.org/en/latest/Dependency-injection.html#asp-net-core


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...