如何在AutoMapper中使用.include()?

时间:2019-05-01 12:01:48

标签: c# asp.net-core automapper

我正在我的应用程序中实现AutoMapper,以针对不同需求具有不同的视图。到目前为止,我或多或少都只是使用DomainModel。

但是当我将AutoMapper用于ViewModel时,如何处理.include()相关数据?

Startup.cs:

services.AddAutoMapper(typeof(AutoMapperProfiles));

AutoMapperProfiles.cs:

public class AutoMapperProfiles : Profile
{

    public AutoMapperProfiles()
    {

        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Product, ProductVM>();
        });

        Mapper.Configuration.AssertConfigurationIsValid();

    }

}

我的模特:

public class Product
{
    public Guid id { get; set; }
    public string Name { get; set; }
    public Guid CategoryId { get; set; }
}

public class ProductVM
{
    public Guid id { get; set; }
    public string Name { get; set; }
    public Guid CategoryId { get; set; }
    [ForeignKey("CategoryId")]
    public ProductCategory ProductCategory { get; set; }
}

public class ProductCategory
{
    public Guid Id { get; set; }
    public string Name ( get; set; }
}

OnGet:

var products = await _dbContext.Products.ProjectTo<ProductVM>(_mapper.ConfigurationProvider).Include(x => x.ProductCategory).ToListAsync();

1 个答案:

答案 0 :(得分:0)

如果您的姓名完全匹配,请尝试以下操作:

CreateMap<Product, ProductVM>().ForMember(p => p.Tags, opt => opt.Ignore());