Как использовать .Include () с AutoMapper? - PullRequest
1 голос
/ 01 мая 2019

Я использую 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 голосов
/ 01 мая 2019

Попробуйте, если ваши имена точно совпадают:

CreateMap<Product, ProductVM>().ForMember(p => p.Tags, opt => opt.Ignore());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...