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

问题描述 投票:1回答:1

我正在我的应用程序中实现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();
c# asp.net-core automapper
1个回答
0
投票

如果您的名字完全匹配,请尝试此操作:

CreateMap<Product, ProductVM>().ForMember(p => p.Tags, opt => opt.Ignore());
© www.soinside.com 2019 - 2024. All rights reserved.