codebyevisla
codebyevisla

Reputation: 21

Missing map CreateMap exception for related entity (AutoMapper & code first)

I'm struggling with Automapper conventions. How are you mean't to include the related entities in your dto's from code first? I've gone through many examples from various times in Automappers history but nothing works so far. The one that makes most sense is this:

<package id="AutoMapper" version="9.0.0" targetFramework="net48" />

[Table("Product")]
public partial class Product
{
    public Product()
    {
        ProductOptions = new HashSet<ProductOption>();
    }

    public int Id { get; set; }

    public byte ProductTypeId { get; set; }

    [StringLength(255)]
    public string ProductName { get; set; }

    public virtual ICollection<ProductOption> ProductOptions { get; set; }
}

[Table("ProductOption")]
public partial class ProductOption
{
    public int Id { get; set; }

    public int ProductId { get; set; } //Foreign key to Product.Id

    [Required]
    [StringLength(255)]
    public string OptionName { get; set; }
}


public class ProductBase
{
    public int Id { get; set; }
    public byte ProductTypeId { get; set; }
    public string ProductName { get; set; }
    public ProductOptionBase ProductOptionsBase { get; set; }
}

public class ProductOptionBase
{
    public int Id { get; set; }
    public int ProductId { get; set; } 
    public string OptionName { get; set; }
}


        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Product, ProductBase>().IncludeMembers(po => po.ProductOptions);
            cfg.CreateMap<ProductOption, ProductOptionBase>();
        });
        var mapper = config.CreateMapper();


        using (var _db = new DataContext())
        {
            return _db.Products.Include(po => po.ProductOptions).ProjectTo<ProductBase>(config).ToList();
        }

Missing map from System.Collections.Generic.ICollection1[Model.ProductOption] to DataContracts.ProductBase. Create using CreateMap<ICollection1, ProductBase>

On var config line

Upvotes: 1

Views: 2157

Answers (1)

codebyevisla
codebyevisla

Reputation: 21

The Config should have been:

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Product, ProductBase>()
             .ForMember(pob => pob.ProductOptionsBase, opts => opts.MapFrom(po => po.ProductOptions));
            cfg.CreateMap<ProductOption, ProductOptionBase>();
        });

There is also no need to use .Include(po => po.ProductOptions)

Upvotes: 1

Related Questions