Osama Abu Baker
Osama Abu Baker

Reputation: 44

EF Core : Foreign key returns null value : Repository Pattern

I've a dotnet core web API that's using Repository Pattern and AutoMapper to mapping resources to models .., Here is the InMemoryDatabase Implementation:

The Entity Product also implement HasData Attribute

as shown below it's a ProducRepository That use EntityFrameworkInclude()method to include category Data

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

I implement category service for HttpGet and prepare the method that get data in ProductControllerhere is the get method

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

in ProductResource i passed CategoryResource in this way

 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; }
}

That means when I run the Product Get Requestthe CategoryResourcemust be executed beside ProductResourse but it returns null just like this:

enter image description here

Upvotes: 0

Views: 315

Answers (1)

Osama Abu Baker
Osama Abu Baker

Reputation: 44

The main idea here that the product and ProductResource just they are mapping for a DescriptionAttribute not for the include

 // 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));

Upvotes: 1

Related Questions