我正在我的应用程序中实现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());