Get Parent based on string value and all its children with Entity Framework Core

entity-framework-core linq

Question

I'm currently getting an object based on a string property like this:

return DbContext.Products.FirstOrDefault(p => p.Route == route);

This is working correctly but I now need to get its child objects (Benefits) that are related in the model like this:

public IList<Benefit> Benefits { get; set; }

How can I get this product and all its child benefits?

Something like this, but this doesn't work:

return DbContext.Products.Include("Benefits")FirstOrDefault(p => p.Route == route);

Thanks

1
0
1/19/2019 2:48:59 PM

Accepted Answer

Can you try like below:

return DbContext.Products.Include(x=>x.Benefits).FirstOrDefault(p => p.Route == route);

And in startup class:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}
1
1/19/2019 5:40:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow