EF核心:外键返回空值:存储库模式

时间:2020-08-11 13:31:54

标签: .net api .net-core

我有一个dotnet core web api,它使用Repository PatternAutoMapper将资源映射到模型.., 这是InMemoryDatabase的实现 The Entity Product also implement HasData Attribute 如下所示,这是一种ProducRepository使用EntityFramework Include()方法来包含类别数据

    public async Task<IEnumerable<Products>>ListAsync(){
        return await _context.Products.Include(p=>p.Categories).ToListAsync();
    }

我为HttpGet实现类别服务,并准备在ProductController中获取数据的方法,这里是get方法

    [HttpGet]
    public async Task<IEnumerable<ProductResource>>ListAsync(){
        var products=await _ProductService.ListAsync();
        var resource = _mapper.Map<IEnumerable<Products>,IEnumerable<ProductResource>>(products);
        return resource;
    }

ProductResource中,我以这种方式通过了CategoryResource

 public class ProductResource
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int QuantityInPackage { get; set; }
    public string UnitOfMeasurement { get; set; }
    public CategoryResource categoryResource { get; set; }
}

这意味着当我运行产品Get Request时,CategoryResource必须在ProductResourse旁边执行,但它会返回null,就像这样

enter image description here

1 个答案:

答案 0 :(得分:1)

这里的主要思想是productProductResource只是映射DescriptionAttribute而不是包含

 // Mapping Description Attribut
 CreateMap<Products,ProductResource>()
            .ForMember(src=>src.UnitOfMeasurement,
                
 opt=>opt.MapFrom(src=>src.UnitOfMeasurement.ToDescriptionString()));

// Mapping Categories Table
        CreateMap<Products,ProductResource>()
            .ForMember(dto=>dto.Categories,
                conf=>conf.MapFrom(p=>p.Categories));