简体   繁体   English

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

[英]How to use .Include() with AutoMapper?

I'm implementing AutoMapper in my app to have different views for different needs. 我在我的应用程序中实现了AutoMapper,以针对不同需求具有不同的视图。 Until now I've more or less just used the DomainModel. 到目前为止,我或多或少都只是使用DomainModel。

But when I use AutoMapper for my ViewModel, how do I then .Include() related data? 但是,当我将AutoMapper用于ViewModel时,如何处理.Include()相关数据?

Startup.cs: Startup.cs:

services.AddAutoMapper(typeof(AutoMapperProfiles));

AutoMapperProfiles.cs: AutoMapperProfiles.cs:

public class AutoMapperProfiles : Profile
{

    public AutoMapperProfiles()
    {

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

        Mapper.Configuration.AssertConfigurationIsValid();

    }

}

My model: 我的模特:

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: OnGet:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM