簡體   English   中英

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

[英]How to use .Include() with 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();

如果您的姓名完全匹配,請嘗試以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM